Using JustMock Commercial Edition you can easily mock out calls to MessageBox.Show(). This can come in handy if you are testing code that bases its execution path on a MessageBox’s result. Also, it is unlikely you want the MessageBox to actually pop up while running your tests. Let’s see how we can accomplish this!
The first thing I do is create a variable to hold the expected MessageBox result. Then I arrange the static Show(string) method of MessageBox. I tell the method to set a local variable “called” to true instead of calling the Show() method’s original implementation by using JustMocks DoInstead feature. Following that we tell the method to return our expected result, DialogResult.Ignore in this case.
The line after Mock.Arrange actually calls MessageBox.Show passing in a test string. Normally when a MessageBox.Show is a little modal form would pop up, and would require the user to click the “OK” button, however using JustMock we have changed the Show method’s execution path, and all MessageBox.Show will do during this test is set the “called” variable to true. We wrap up the test by asserting our expectations. And we get green!
The previous test shows us that JustMock can successfully arrange MessageBox.Show, but it doesn’t do much besides test the JustMock framework. So lets see how we can apply this to a real scenario.
Lets say I have the following form:
As we can see there are two paths through the DoIt method in our form. I want to test BOTH paths, but the execution path is based on the pesky DialogResult the MessageBox returns! Using the code above we can quickly create tests that will navigate us down both execution paths for the DoIt method.
The test code is slightly longer in these tests as we are mocking out the MessageBox.Show overload that allows you to specify the buttons it will show. The first test simulates the user hitting the “OK” button on the messagebox, and the second test simulates the user hitting “Cancel.”
To run these tests you will need the commercial version of JustMock, and make sure to enable the profiler:
Hopefully this helps you out in the future! Happy Coding!
Subscribe to be the first to get our expert-written articles and tutorials for developers!