HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Unit testing IValueConverter

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
ivalueconvertertestingunit

Problem

I am just starting to implement unit testing into my project and familiarizing myself with NUnit. I have added unit tests for encryption/decryption methods that I have implemented, and am looking for more things to start testing for in my existing code before moving forward.

The most basic classes that I have are my IValueConverters, so I thought it would be a good place to start.

Here is my first test:

[TestFixture]
public class ConverterUnitTest
{
    [TestCase]
    public void BooleanToVisibilityConverterTest()
    {
        var btvConverter = new BooleanToVisibilityConverter();

        Assert.That(btvConverter.Convert(true, typeof(Visibility), null, "en-us").Equals(Visibility.Visible));
        Assert.That(btvConverter.Convert(false, typeof(Visibility), null, "en-us").Equals(Visibility.Collapsed));
    }
}


As you can see, this test is just ensuring that true returns Visibility.Visible and false returns Visibility.Collapsed. What I am wondering is, does it make sense to have multiple Asserts in one test, or should I split them up into multiple tests even though they are both testing the same converter? Also, is it a good practice to test converters?

Solution

This is a good unit test. It may seem like a trivial case to test a boolean response, but wrapping this in a test ensures that you always get the correct response. What if you decide to refactor the internals of BooleanToVisibilityConverter down the road? With this test, you can always be confident that it's behaving correctly.

To me, the two assertions look like they belong together. As a matter of style, you could split the test up so that you have two tests with a straight AAA (Arrange, Act, Assert) pattern - one for true, one for false. In my opinion, that would be a little excessive. I like a test that looks like this because it is clear and quick.

If you were writing a test of a converter that had many possible outputs and multiple input conditions (for example), then you definitely should consider splitting it up and testing each condition separately. For now, you're on the right track.

Context

StackExchange Code Review Q#87610, answer score: 7

Revisions (0)

No revisions yet.