JUnit

JUnit in java is nothing but a programming technique or testing framework to perform the unit test for the code written in a new class or a new method added to an existing class in java. JUnit plays a vital role in the test driven development process of an application.

The basic motto behind writing Junits is not to find bugs or find some regression. This is basically used to unit test the code which is being written based on certain boundary conditions and also to ensure that the written code is covered with all possible scenarios as per the requirements. Of course, it may not be possible to get 100% coverage from the Junits for the code, but still it can be used perform the test to a maximum extent.

Though it is pretty simple to unit test the code by using Junits, it is still a really challenging tasks for developers in order to unit test the code based on the boundary conditions. Hence, writing a good Junit is really essential. Below are the list of tips which will really help developers to write a good Junit:

  • Naming a test case is really an important step. Because. Test case name should be easily denotes what it is going to test (module/scenario which is to be tested).
  • Separate Junit should be written for each test. i.e. your test only one code at a time.
  • As mentioned above, it is difficult to get 100% code coverage through the Junits all the time. Hence, it is not feasible to developers to invest more time on trivial operations. i.e. Junits for getXXX() and setXXX()
  • Always unit test the core classes/methods which will be used by many parts of the application.
  • Ensure that your Junits are aligned with the requirements of the application.
  • Do not make unnecessary assertions in the tests. Keep only one main assertion which really results in the unit test of the code.
  • It is very much essential to write Junits which breaks the thread safety.
  • Make a good use of @Before and @After for all pre/post requisites of your tests.
  • If a test class is growing to a bigger one, then it is better to have a new test class.
  • Do not use print statements in the test cases.
  • Try to keep the Junits independent of database and file systems.
  • Never skip your test cases from being tested. There might be Junits which are incomplete and needs some more time. Most of the scenarios, developers skips such test cases by using @Ignore, which is really a bad practice. If this is the case, better remove the test cases and add them only when they are completely done.
  • It is better to write test cases for each scenario, rather being in an assumption that the dependent test cases will also be tested.
  • Do not use any static member in a test class, as every test should be independent of each other.
  • Integrate your test cases to be executed during the build by using maven/ANT tools. This is will ensure the reliability.

Comments

Questions? Comments? Suggestions? Let us know!! Like / Subscribe / Follow for more updates.