Reputation: 858
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
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:
Upvotes: 3
Reputation: 12956
Test:
this.InitiateRecording()
is calledBubbleUiException
when this.InitiateRecording()
is calledException
that is not BubbleUiException
when this.InitiateRecording()
is calledMessageBox.Show
so you can test that it prints what you expect when the exceptions are thrown.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