Wednesday 21 January 2015

Unit Testing: How to write test cases?

Unit tests for test functions in isolation, i.e. you call a function with mock up-parameters and verify the results. Ideally, you check both success and failure response. A schematic example. Say you have a function like this:
def myfunc(a, b):
    return a / b
Then a unit test could be like this:
def test_myfunc():
    result = myfunc(4, 2)
    if result != 2:
        raise AssertionError("Wrong result: should have been 2, but was %s." % result)
So you're writing another function to call the function that is to be tested, with parameters for which you know the result, in order to prove that the function really returns the expected result.
Typically, you should have at least one test call for each distinct type of case - e.g. for myfunc() this would additionally be the cases where either parameter is 0.

Now, in order to write unit tests for any module, you need to look at each function and understand what results it should deliver for which input - and try to find a way to inspect and verify the result. Then identify the assertions (=expected results) for each type of case, and encode it as a test case

You do not need to test the overall functionality - all we need to know is whether the parts still do after the refactoring what they did before, the results are still correct, and no new bugs have been introduced (=regression testing)

No comments:

Post a Comment