Java Unit Testing: Best Practices

By Dipankar Das, Gaea News Network
Wednesday, November 18, 2009

java_startingJunit is a java based tool that offers good, robust test facility. But, if you use it in a wrong way, it produces horrendous output. This article gives you some insight to test java code with the help of the JUnit toolkit.

  • The name of the method should start with the word ‘test’. The return type of the method should be null. The method shouldn’t have any parameter.
  • You should write a test case for the method which is less dependent on sub method. If you write a test case for dependent methods, your test may fail because the sub method can return wrong value. So, it may take longer to find out the source of the problem.
  • Each unit test should be independent of other test. If you write one unit test for mutilple methods then the result may be confusing.
  • Test behavior is more important than methods. Each test case has to be in the same package as the code to be tested. For example if we want to create  classes in root.baseclasses,then test cases must be in the same package.
  • Although, it is nice to cover most of the code in the test cases, it is not advisable to use 100% of the code. If the method is too simple then there is no point of writing unit test for it. For example, testing an ordinary Getter or Setter method is not advisable.
  • You should use object oriented best practice for your test code. It is imperative to write your test cases as first class code. You should bring all of the common functionalities in the base class. That way you can eliminate duplicate code, long methods etc.
  • You should use proper method name. It will be easier for you to understand the terminology afterwards. Simultaneously, it is going to be easier for the team to maintain the code in future.
  • The Junit framework automatically handles the exception. It is good idea not to throw an exception in a test that shouldn’t throw an exception. Otherwise, it can hide bugs which may be discovered much later stage. That can be waste of unnecessary overhead.
  • JUnit is an effective tool for unit testing of java code. But, it doesn’t provide all of the functionalities to test your code. So, you need an additional test tool. Some of the tools are DBunit, Selenium etc that can be used as an extension of junit.
  • You shouldn’t rely completely on System.out.println() method to figure out the success of the test. Rather , you can rely upon the ‘assert’ method of junit so that you can run the automated test  and that way the tester doesn’t need to monitor the test in person all the time.
will not be displayed