我正在使用 C# .Net Windows 窗体制作桌面/本地应用程序,我需要对在执行某些过程时通过消息与用户交互的类执行一些测试,并使用单元测试覆盖流程需要检查是否调用了 messageBox 以及调用了哪些参数。谁能帮帮我,我该怎么办?
我尝试使用 MessageBox 类执行此操作,但我做不到,而且我不想在我的测试项目中包含 Windows 窗体引用。
您必须将消息框包装在可注入服务中。
public interface IDialogs
{
bool ShowMessageBox(string message, string? title = null);
}
// Possible implementation.
class MyDialogs : IDialogs
{
public bool ShowMessageBox(string message, string? title = null)
=> MessageBox.Show(message, title ?? "Default Caption") == DialogResult.OK;
}
// Mocked implementation
// (using C# 12 primary constructor, but works with normal constructor and field as well)
class MockedDialogs(bool expectedResult) : IDialogs
{
public bool ShowMessageBox(string message, string? title = null)
=> expectedResult;
}