Site icon TestingDocs.com

Beginners Guide for writing Good Unit Tests

Overview

In this post, beginners Guide for writing Good Unit Tests, we will discuss some guidelines for writing good JUnit tests.

Naming convention:

Name your tests properly as per the naming convention (often mentioned in the organization Coding standard documents). Test case class names should reflect the class they are intended to test. Also, this avoids confusion and makes your tests and test classes evident of functionality that they intended to test. Furthermore, test case methods should reflect the scenario they are intended to test.

Example

Example shown below:

public class CalculatorTests { 
  @Test 
  public void addIntegerTest()
  {
   ....
   }
 
  @Test 
  public void multiplyIntegerTest()
  {
    ...
   }
 
  ..
  ..
  ....
}


Full Automated & CI runs

Unit tests should be fully automated. Good unit tests are tests that require no manual intervention. A continuous integration Jenkins unit tests build needs to be run whenever application code changes.

Do not hard code

Do not hard code test data in your test cases. ( dates , config filenames , number formats, etc )

Small and Independent

Tests should be independent of each other. Avoid coupling between tests. Check a single thing at a time.Don not complicate the tests. In addition, coupled testcases make debugging difficult and somewhat shield changes to them.

Do not assume

Do not assume the order in which tests run. By default, JUnit do not run tests in a predictable way. Furthermore, the order may change from JVM to JVM.

Use proper asserts

Use proper asserts that give verbose information when things go wrong as shown in below pictures.

Prefer above than below one.

 

JUnit Tutorial: https://www.testingdocs.com/junit-tutorial/

More information on JUnit can be found on the official website: https://junit.org

Exit mobile version