Question

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".

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?

Was it helpful?

Solution

You have to inject something that will stub the Show User Dialog call. 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);
}

OTHER TIPS

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:

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:

[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"));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top