简体   繁体   English

为提示消息框的方法编写NUnit测试用例

[英]Write NUnit Test case for a method which prompts a message box

I have a method with the following structure: 我有一个具有以下结构的方法:

bool myMethod(some arguments)
{

   //Show User Dialog

}

The user dialog is shown which has 4 buttons, "Yes", "Yes To All", "No" , "No To All". 显示用户对话框,其中有4个按钮,“是”,“全是”,“否”,“全是”。

When I run the test case, It shows the user dialog, but test case do not proceed until user clicks on any button. 当我运行测试用例时,它会显示用户对话框,但在用户单击任何按钮之前,测试用例不会继续。 How do we cover such methods using nUnit Test case? 我们如何使用nUnit测试用例来涵盖这些方法?

You have to inject something that will stub the Show User Dialog call. 你必须注入一些将存根 Show User Dialog调用的东西。 Then you can within your test set the stub to the desired user answer and call your method: 然后,您可以在测试中将存根设置为所需的用户答案并调用您的方法:

public class MyClass
{
    private IMessageBox _MessageBox;

    public MyClass(IMessageBox messageBox)
    {
        _MessageBox = messageBox;
    }

    public bool MyMethod(string arg)
    {
        var result = _MessageBox.ShowDialog();
        return result == DialogResult.Ok;
    }
}

internal class MessageBoxStub : IMessageBox
{
    DialogResult Result {get;set;}

    public DialogResult ShowDialog()
    {
        return Result;
    }
}

[Test]
public void MyTest()
{
    var messageBox = new MessageBoxStub() { Result = DialogResult.Yes }
    var unitUnderTest = new MyClass(messageBox);

    Assert.That(unitUnderTest.MyMethod(null), Is.True);
}

It depends on what you want to test. 这取决于你想要测试的内容。 If you are just concerned about the flow of the application after the user response (they press YES, NO etc) then you could just stub out a "fake" response: 如果你只关心用户响应后的应用程序流(他们按YES,NO等),那么你可能只是存在一个“假的”响应:

public void MessageBox_UserPressesOK()
{
var result == Dialog.OK
    // test
}

And so on. 等等。

You can use Typemock Isolator (note that this is not a free tool), here's your exact example from their web page: 您可以使用Typemock Isolator (请注意,这不是免费工具),这是您网页上的确切示例:

[Test]
public void SimpleTestUsingMessageBox()
{
 // Arrange
 Isolate.WhenCalled(()=>MessageBox.Show(String.Empty)).WillReturn(DialogResult.OK);

 // Act
 MessageBox.Show("This is a message");

 // Assert
 Isolate.Verify.WasCalledWithExactArguments(()=>MessageBox.Show("This is a message"));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM