Unit Testing: Hello, World!

The “Hello, World!” of unit tests typically involves a function that accepts inputs and provides an expected output. Consider the following Calculator class:

public class Calculator
{
    public static int Add(int x, int y)
    {
        return x + y;
    }
    public static int Divide(int dividend, int divisor)
    {
        return dividend / divisor;
    }
}

Writing unit tests for the Add method is simple and straightforward. We can declare our inputs, come up with the expected output, execute the function and verify the result.

[TestMethod]
public void AddTest()
{
    int x = 1;
    int y = 2;
    int expected = 3;
    int actual = Calculator.Add(x, y);
    Assert.AreEqual(expected, actual);
}

The Add method is so simple that there isn’t much more you can do with it, so let’s take a look a the Divide method. Similarly to the Add method, we can write a simple unit test to verify our core behavior.

[TestMethod]
public void DivideTest()
{
    int dividend = 10;
    int divisor = 2;
    int expected = 5;
    int actual = Calculator.Divide(dividend, divisor);
    Assert.AreEqual(expected, actual);
}

Now that we have that out of the way, let’s deal with an exception case: division by zero. Before we can test or code, we must decide what we want our application to do in this scenario. I have decided that application should simply throw the default divide-by-zero exception, so let’s write a test for it to help ensure that this functionality isn’t lost with future changes.

[TestMethod]
[ExpectedException(typeof(System.DivideByZeroException))]
public void DivideTest_DivisionByZero()
{
    int dividend = 10;
    int divisor = 0;
    int actual = Calculator.Divide(dividend, divisor);
}

By decorating the test method with the ExpectedException attribute, the test will fail if the exception is not thrown.

You can see that writing unit tests for these something-in-something-out functions can be very easy. Try to test as many different scenarios as you can come up with. Some common situations to consider are minimums, maximums, default values, and nulls. Write skeleton tests up-front to help you remember relevant scenarios to be handled by your code.

Advertisements

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s