JUnit for Functions with Void Return Values

Posted by RobotNerd on Stack Overflow See other posts from Stack Overflow or by RobotNerd
Published on 2010-05-27T14:51:09Z Indexed on 2010/05/27 14:51 UTC
Read the original article Hit count: 208

I've been working on a Java application where I have to use JUnit for testing. I am learning it as I go. So far I find it to be useful, especially when used in conjunction with the Eclipse JUnit plugin.

After playing around a bit, I developed a consistent method for building my unit tests for functions with no return values. I wanted to share it here and ask others to comment. Do you have any suggested improvements or alternative ways to accomplish the same goal?

Common Return Values

First, there's an enumeration which is used to store values representing test outcomes.

public enum UnitTestReturnValues
{
    noException,
    unexpectedException
    // etc...
}

Generalized Test

Let's say a unit test is being written for:

public class SomeClass
{
    public void targetFunction (int x, int y)
    {
        // ...
    }
}

The JUnit test class would be created:

import junit.framework.TestCase;
public class TestSomeClass extends TestCase
{
    // ...
}

Within this class, I create a function which is used for every call to the target function being tested. It catches all exceptions and returns a message based on the outcome. For example:

public class TestSomeClass extends TestCase
{
    private UnitTestReturnValues callTargetFunction (int x, int y)
    {
        UnitTestReturnValues outcome = UnitTestReturnValues.noException;
        SomeClass testObj = new SomeClass ();
        try
        {
            testObj.targetFunction (x, y);
        }
        catch (Exception e)
        {
            UnitTestReturnValues.unexpectedException;
        }
        return outcome;
    }
}

JUnit Tests

Functions called by JUnit begin with a lowercase "test" in the function name, and they fail at the first failed assertion. To run multiple tests on the targetFunction above, it would be written as:

public class TestSomeClass extends TestCase
{
    public void testTargetFunctionNegatives ()
    {
        assertEquals (
            callTargetFunction (-1, -1),
            UnitTestReturnValues.noException);
    }

    public void testTargetFunctionZeros ()
    {
        assertEquals (
            callTargetFunction (0, 0),
            UnitTestReturnValues.noException);
    }

    // and so on...
}

Please let me know if you have any suggestions or improvements. Keep in mind that I am in the process of learning how to use JUnit, so I'm sure there are existing tools available that might make this process easier. Thanks!

© Stack Overflow or respective owner

Related posts about unit-testing

Related posts about junit