Testing if a messagebox was successfully shown in a unit test

3.5k Views Asked by At

hopefully it's pretty simple but I'm stuck trying to figure this out.

If I have a simple class with a method which is supposed to do something and then show a messagebox via MessageBox.Show("") when some values are in a certain state, how do I write a test/tests that can detect if a the messagebox was shown when expected and/or not shown when not expected?

2

There are 2 best solutions below

3
On

You can't really test that though Unit tests. There is an easy way to test if the code was called correctly though.

I would hide showing the MessageBox behind an interface. Then mock that interface and create a counter or something like that in your mock implementation. Of course you can make this as specific as you need, providing the message shown, etc.

2
On

You shouldn't test that a MesssageBox appears, though it is possible to do so with one or another UI automation framework (like https://msdn.microsoft.com/en-us/library/ms747327(v=vs.110).aspx).

But it won't be a unittest. It would be an automated UI test.

So, if you want to create a proper unittest, then your class should be injectable with some

public interface IMessageBox
{
    void Show(String message);
}

public class SUT
{
    public SUT(IMessageBox messageBox)
    {   
        this._messageBox = messageBox;
    }

    public void Test()
    {
        this._messageBox.Show("TEST);
    }
}

So that you can mock that IMessageBox inside the unittest.

For example, with Moq:

[TestMethod]
public void Test()
{
    // Arrange
    var messageBox = new Mock<IMessageBox>();
    messageBox
        .Setup(m =>
            m.Show("TEST))
        .Verifiable();

    var sut = new SUT(messageBox.Object);

    // Act
    sut.Test();

    // Verify
    messageBox.Verify();        
}