Write a NUnit test case for a method that requests a message box

I have a method with the following structure:

bool myMethod(some arguments)
{

   //Show User Dialog

}

A user dialog box appears with 4 buttons: Yes, Yes for all, No, No for all.

When I run the test case, it shows the user dialog box, but the test case does not continue until the user clicks on any button. How do we cover such methods using the nUnit Test case?

+3
source share
3 answers

You must enter something that drowns the call Show User Dialog. Then, in your test mode, you can set the stub to the userโ€™s desired response 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);
}
+2
source

, . ( YES, NO ..), "" :

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

.

+1

You can use Typemock Isolator (note that this is not a free tool), here is your exact example from your web page:

[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"));
}
+1
source

All Articles