Part 3 – Annotations in JUnit

Annotations in JUnit

What have we learned so far

Part 1 – What is Unit Testing?
https://www.onlyfullstack.com/what-is-unit-testing/

Part 2 – What is JUnit? How to use JUnit?
https://www.onlyfullstack.com/what-is-junit-how-to-setup-junit-in-eclipse/

How to define a test in JUnit?

A JUnit test is a method contained in a class which is only used for testing. This is called a Test class. To define that a certain method is a test method, annotate it with the @Test annotation.

This method executes the code under test. You use an assert method, provided by JUnit or another assert framework, to check an expected result versus the actual result. These method calls are typically called asserts or assert statements.

You should provide meaningful messages in assert statements. That makes it easier for the user to identify and fix the problem. This is especially true if someone looks at the problem, who did not write the code under test or the test code.

@Test
public void isValidEmployee_withNullEmployee() {
    assertEquals(new Double(0.0), employeeService.calculateTax(null));
}

Annotations used in Junit

Annotation
Description
@Test
Identifies a method as a test method.
@Before
Executed before each test. It is used to prepare the test environment (e.g., read input data, initialize the class).
@After
Executed after each test. It is used to clean up the test environment (e.g., delete temporary data, restore defaults). It can also save memory by cleaning up expensive memory structures.
@BeforeClass
Executed once, before the start of all tests. It is used to perform time intensive activities, for example, to connect to a database. Methods marked with this annotation need to be defined as static to work with JUnit.
@AfterClass
Executed once, after all tests have been finished. It is used to perform clean-up activities, for example, to disconnect from a database. Methods annotated with this annotation need to be defined as static to work with JUnit.
@Ignore or @Ignore("Why disabled")
Marks that the test should be disabled. This is useful when the underlying code has been changed and the test case has not yet been adapted. Or if the execution time of this test is too long to be included. It is best practice to provide the optional description, why the test is disabled.
@Test (expected = Exception.class)
Fails if the method does not throw the named exception.
@Test(timeout=100)
Fails if the method takes longer than 100 milliseconds.

Sample class and its test cases

Let’s write some business logic to add the test cases:
Business Logic Class:
package com.onlyfullstack.unittesting.service;

import java.util.Collections;
import java.util.Map;

import com.onlyfullstack.unittesting.bean.Employee;

public final class EmployeeService {

    private Map<Integer, Employee> employeeMap = Collections.singletonMap(1, new Employee());

    public boolean isValidEmployee(Employee employee) {
        boolean isValid = false;
        if(employee != null) {
            if(employee.getId() != null && employee.getName() !=null) {
                isValid = true;
            }
        }
        return isValid;
    }

    public Double calculateTax(Employee employee) {
        Double tax = 0.0;
        if(employee!=null && employee.getSalary() >0) {
            if(employee.getSalary() < 500000) {
                tax = employee.getSalary() * 0.05;
            } else if(employee.getSalary() > 500000 && employee.getSalary() < 1000000) {
                tax = employee.getSalary() * 0.1;
            } else {
                tax = employee.getSalary() * 0.2;
            }
        }
        return tax;
    }

    public Employee getEmployeeFromId(Integer id) {
        return employeeMap.get(id);
    }
}

Test Class

package com.onlyfullstack.unittesting.service;

import com.onlyfullstack.unittesting.bean.Employee;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import static org.junit.Assert.*;

/**
 * This class contains Unit Test cases of {@link EmployeeService}
 */
public class EmployeeServiceTest {

    private EmployeeService employeeService = new EmployeeService();

    private Employee employee = null;

    @BeforeClass
    public static void beforeClass() {
        System.out.println("Executing Before Class");
    }

    @Before
    public void before() {
        System.out.println("Executing Before");
        employee = new Employee();
        employee.setSalary(1000000.0);
    }

    @AfterClass
    public static void afterClass() {
        System.out.println("Executing After Class");
    }

    @After
    public void after() {
        System.out.println("Executing After");
    }

    @Test
    public void isValidEmployee_withNullEmployee() {
        System.out.println("Entered in isValidEmployee_withNullEmployee");
        assertEquals(new Double(0.0), employeeService.calculateTax(null));
        System.out.println("Exited from isValidEmployee_withNullEmployee");
    }

    @Test
    public void isValidEmployee_withNegativeSalary() {
        System.out.println("Entered in isValidEmployee_withNegativeSalary");
        employee.setSalary(-2.0);
        assertEquals(new Double(0.0), employeeService.calculateTax(null));
        System.out.println("Exited from isValidEmployee_withNegativeSalary");
    }
}
Let’s run the test cases with Eclipse run with Junit test option.

Output
Executing Before Class
Executing Before
Entered in isValidEmployee_withNegativeSalary
Exited from isValidEmployee_withNegativeSalary
Executing After
Executing Before
Entered in isValidEmployee_withNullEmployee
Exited from isValidEmployee_withNullEmployee
Executing After
Executing After Class
@Before and @After are called for every test case.
@BeforeClass and @AfterClass are called once

Source Code
Download the source code of JUnit tutorial from below git repository :
unit-testing-and-integration-testing-with-spring-boot

Let’s go to our next tutorial where we will discuss below points :

Part 4 – JUnit Assert Methods

In this tutorial, we will understand below topics –

– Assert Methods
1. assertEquals()
2. assertTrue() + assertFalse()
3. assertNull() + assertNotNull()
4. assertSame() and assertNotSame()
5. assertThat()