Showing posts with label Junit. Show all posts
Showing posts with label Junit. Show all posts

Tuesday, January 25, 2011

Junit Best Practices with detailed examples - Must for every Java Developer

This is second in our tutorial series of junit.
If you wish to retouch junit basics : http://codingbasics.blogspot.com/2011/01/junit-tutorial-1-junit-with-example.html
In this blog, we will touch up some very important best practices for junits.

Unit Test cases need to be independent:

Each unit test should be independent of all other tests.  A unit test should execute one specific behavior for a single method.
Validating behavior of multiple methods is problematic as such coupling can increase refactoring time and effort.

 Consider the following example:

void testAdd(){
     int val1 = myClass.add(1,2);
     int val2 = myclass.add(-1,-2);
     assertTrue (val1 - val2 == 0);
}

If the assertions fails in this case, it will be difficult to determine which invocation of add() caused the problem.

If you want to test a method for multiple behaviors then one test method must be written for each scenario.
This will make the unit test case focus on the particular behavior of the method with great clarity and maintainability.
Please see the self-explanatory following example in testing a method called divide()

public void testNegativeValues()
{
// This method is used to test for negative values scenario.
}

public void testDivideByZero()
{
// The name very well explains what is this test all about.
}

Lets see some more

subversion video