views:

107

answers:

3

What ways can the SampleConfirmationDialog be unit tested? The SampleConfirmationDialog would be exercised via acceptance tests, however how could we unit test it, seeing as MessageBox is not abstract and no matching interface?

public interface IConfirmationDialog
{
    /// <summary>
    /// Confirms the dialog with the user
    /// </summary>
    /// <returns>True if confirmed, false if not, null if cancelled</returns>
    bool? Confirm();
}


/// <summary>
/// Implementation of a confirmation dialog
/// </summary>
public class SampleConfirmationDialog : IConfirmationDialog
{
    /// <summary>
    /// Confirms the dialog with the user
    /// </summary>
    /// <returns>True if confirmed, false if not, null if cancelled</returns>
    public bool? Confirm()
    {
        return MessageBox.Show("do operation x?", "title", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes;
    }
}
+4  A: 

You can't, it's untestable in it's current state. For this particular class, there is also no value in unit testing it ... it is but a light wrapper around a built-in framework feature, so all you'd be doing is testing the framework.

If you absolutely must test it, the IConfirmationDialog interface should have another dependency that you can mock up in the unit test.

Joel Martinez
In other words, you want to test the `SampleConfirmationDialog`, not the `MessageBox` class. You can abstract an `IConfirmationProvider`, of which one implementation may use a `MessageBox`, and you can test that `Confirm()` calls `IConfirmationProvider.GetConfirmation()`, but this doesn't help you -- at some level you'll run into that untestable `MessageBox.`
Jay
Yeah, thanks. This one has been bugging me. But you're both right.
Sean B
A: 

You should look into Typemock, a commercial mocking framework that lets you unit test these kinds of situations by using the .NET performance profiling libraries. See their website for more information.

Michael Hedgpeth
A: 

I think it's OK to stop testing it at that level. Your interaction with IConfirmationDialog is more important than verifying that MessageBox.Show is actually getting called. Since that is an interface and is easily mockable, I think you are pretty well covered.

Igor Zevaka