MessageBox in a unit-test

Situation

You want to unit-test a method which uses a MessageBox.

Problem

The MessageBox will pop up and stop the execution of all tests until the user chooses an action (e.g. presses “OK”).

Solution

One way around this issue is mocking the MessageBox class to just return the expected DialogResult, which can be done using an Isolation Framework like Microsoft Moles.

The mocking code could look something like this:

MMessageBox.ShowStringStringMessageBoxButtonsMessageBoxIconMessageBoxDefaultButtonMessageBoxOptions
= (a, b, c, d, e, f) =>
{
  return DialogResult.OK;
};

The one disadvantage is the big performance impact on the compile because a moles assembly needs to be generated for System.Windows.Forms.

Alternative

One alternative is to use the Win-API to find the window of the message box and take control over it. This means moving the overhead from the compile time to the implementation time and code.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.