Java Unit Testing Quick Reference

What is Unit Testing?

Unit testing simply verifies that individual units of code (mostly functions) work as expected. In Unit Testing, we are verifying the correctness of a method in isolated manner and mainly focused on the its behavior. It is mainly performed by developer and ensures that method written by them or some other developer works as expect even when the the provided inputs are not correct.

Why to do Unit Testing?

Unit Testing plays a crucial role in application development. Now a days organization following Test Driven approach for developing any application means you should write Test Cases first before writing any code. The quality of unit test cases ensures that application works as expected and there would be less chance of bugs.  Basically the developers of the application write unit test cases for their methods to ensure it works in case of negative scenarios too.

Benefits of Unit Testing

  1. To verify the behavior of a method/function
  2. Unit Testing ensures the behavior of a function to remain same in case of refactoring or changes in future.
  3. Through Unit Testing one can get aware of the functionality.
  4. Application runs smoothly in case of negative scenarios too.

How to do Unit Testing

There are various frameworks which provide the API to write unit test cases for Java Application.

  1. JUnit 
  2. Mocking Framework – Mockito

JUnit

JUnit is a unit testing framework for Java programming language. It plays a pivotal role for test-driven development. It provides various annotations to write test cases.

Features of JUnit Framework

  1. Open Source Framework for unit testing of java application.
  2. Provides annotations for define test cases.
  3. Provides assertions for testing expected results.
  4. Provides test runners for running tests.
  5. Easy to use.

JUnit 5 Annotations

  1. @BeforeAll – Run once before any of the test methods in the class, public static void
  2. @AfterAll – Run once after all the tests in the class have been run, public static void
  3. @BeforeEach – Run before @Test, public void
  4. @AfterEach – Run after @Test, public void
  5. @Test – This is the test method to run, public void
  6. @Disabled – To disable a test case
  7. @DisplayName – To display name custom name for a test method or class
  8. @ParameterizedTest – Denotes that a method is a parameterized test. It used for executing same test cases with several inputs.

Read More

Assertion

An assertion method compares the actual value returned by a test to the expected value. JUnit provides Assert class with static methods to be used to define assertions. Some of the assertion methods are following.

  1. void assertTrue(boolean condition) – Verifies that a condition is true.
  2. void assertFalse(boolean condition) –Verifies that a condition is false.
  3. void assertNotNull(Object object) – Verifies that provided object is not null.
  4. void assertNull(Object object) – Verifies that provided object is null.
  5. void assertEquals(boolean expected, boolean actual) – Verifies that both the conditions are equal.
  6. void assertThrows(Class expectedType, Executable executable) –  Verifies that execution of the supplied executable throws an exception of the expectedType and returns the exception.

Example of writing a Simple Test Case

You have to include the following dependencies of Junit 5.

  1. junit-jupiter-api:5.3.1
  2. junit-jupiter-params:5.3.1
  3. junit-jupiter-engine:5.3.1

In src/test/java we have to define Test classes. Now we are here, do unit testing for Calculator class methods. We are here testing the behavior of divide method.

Calculator.java

public class Calculator {
   public int divide(int x, int y){
       return x/y;
   }
}

CalculatorTest.java

In setup method we initialized the calculator instance and annotated with @BeforeEach so that before running each test case it get initialized.

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

import com.startwithjava.Calculator;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
public class CalculatorTest {
    private Calculator calculator;
    @BeforeEach
    public void setUp(){
        calculator = new Calculator();
    }
    @DisplayName("Test Divide method behavior when divisor is greater than zero")
    @Test public void testDivide_WhenDivisorIsGreaterThanZero_ReturnResult() {
        assertEquals(6, calculator.divide(12,2));
    }
    @DisplayName("Test Divide method behavior when divisor is zero")
    @Test public void testDivide_WhenDivisorIsZero_ThrowException() {
        assertThrows(ArithmeticException.class,()-> calculator.divide(2,0));
    }
}

 

Leave a Reply