priya
priya

Reputation: 858

Unit Testing forms and Events in c#

I want to write Test cases for C# code that triggers events or displays a form to user for input e.g.:

private void CreateRecord_Click(object sender, EventArgs e)
{
    try
    {
        this.InitiateRecording();
    }
    catch (BubbleUiException ex)
    {
        objLog.Error(TextRes.IDC_EShuttleError, ex);
        MessageBox.Show(
            ex.Message,
            TextRes.IDC_EShuttleError,
            MessageBoxButtons.OK,
            MessageBoxIcon.Error);
     }
     catch (Exception ex)
     {
         objLog.Error("Error occurred", ex);
         MessageBox.Show(
             ex.Message,
             TextRes.IDC_Error,
             MessageBoxButtons.OK,
             MessageBoxIcon.Error);
     }
 }

How to write Unit tests for these kind of code using Mbunit?

Upvotes: 0

Views: 1667

Answers (2)

David Arno
David Arno

Reputation: 43254

The "purist" answer is that since it's a private method, it should not be unit tested as it's an implementation detail. You should aim to test public APIs only.

As it is an event handler, you may still want to test it for various reasons. As currently written though, this will be hard to do. The fact that you have a

this.InitiateRecording();

line suggests you haven't properly implemented separation of concerns. Your class for handling events also seems to contain code for handling recording. Secondly, you have hard-coded calls to MessageBox.Show, which will make testing hard as your tests cannot be run in an automatic, stand-alone fashion.

I'd recommend therefore:

  1. Refactor the recording functionality out into a separate class, which can be unit tested.
  2. Inject the MessageBox.Show method into that class, so that it can be stubbed during testing.
  3. Do not test CreateRecord_Click() as it will simply call a method in your new class.

Upvotes: 3

Sam Leach
Sam Leach

Reputation: 12956

Test:

  1. this.InitiateRecording() is called
  2. Force a BubbleUiException when this.InitiateRecording() is called
  3. Force a Exception that is not BubbleUiException when this.InitiateRecording() is called
  4. Wrap MessageBox.Show so you can test that it prints what you expect when the exceptions are thrown.
  5. Test objLog.Error is called.

You can assume that your click event works (that the method is called when the control is clicked) as Microsoft have already tested this.

Upvotes: 0

Related Questions