Search code examples
c#unit-testingmbunit

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?


Solution

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