我正在为我的WPF C#应用程序编写NUnit测试代码.这里有一些我的方法有MessageBox.Show("");但我们不知道如何在代码中处理这个.
请通过提供解决方案帮助我.
谢谢,
您可以创建一种可以在测试中模拟的MessageBoxService.示例代码是:
public class ClassUnderTest
{
public IMessageBoxService MessageBoxService { get; set; }
public void SomeMethod()
{
//Some logic
MessageBoxService.Show("message");
//Some more logic
}
}
interface IMessageBoxService
{
void Show(string message);
}
public class MessageBoxService : IMessageBoxService
{
public void Show(string message)
{
MessageBox.Show("");
}
}
Run Code Online (Sandbox Code Playgroud)
然后在测试中,您可以选择模拟公共属性或创建构造函数来传递模拟的实例.例如,如果您使用Moq,测试可能如下所示:
[Test]
public void ClassUnderTest_SomeMethod_ExpectsSomtething()
{
ClassUnderTest testClass = new ClassUnderTest();
testClass.MessageBoxService = new Mock<IMessageBoxService>().Object;
//More setup
//Action
//Assertion
}
Run Code Online (Sandbox Code Playgroud)