Sunday, December 02, 2007

Unit Testing void Methods - Part 1

Dissection of void Methods without parameters

Methods with void return types incur complexities in writing unit tests. So, we need to characterize the void methods to make sure we have guards against the odds for testability.

A typical void method without any parameter looks like the following

public void DoSomething()
{

//1.modifies some member variables
this.someMemberVariable = 10;

//2.Calls methods of the same class or other classes
someClass.SomeOtherMethod(someArg);

//3.Sometimes throws exception
}


So, we need to make sure we can test all the activities performed by such a method. The following are the illustrative examples showing the unit test solutions case by case

a. To test a method that modifies a member variable we need to write assertions on the member variables accessors. If this is a private member without a getter method then we will overlook it for the same reason as we discard the testing of private members

Note: Examples coming up shortly.

b. If this method calls a method from this class, we need to make sure that the called method is tested. If the called method belongs to anther class then, we can use dependency injection to use a mock for this method or make sure this method is testable.

Note: Examples coming up shortly.

c. If a method throws exception on some certain conditions, we can test for that exception with the appropriate conditions.

Note: Examples coming up shortly.