1. JUnit 5 Project structure

We setup a project structure as below in Eclipse.

Two Java classes need to be tested are MyCalculator and TaxUtil. To test them, we create two test classes named MyCalculatorTest and TaxUtilTest that contain unit test cases. Each test class can be run individually. TestAll is a JUnit Test Suite that is to run both the two individual test classes.

Below is the content of MyCalculator.java:

package com.devspeedup.java.junittutorial;

public class MyCalculator {
	
	public int add(int x, int y) {
		return x + y;
	}
	
	public int substract(int x, int y) {
		return x - y;
	}
}

Below is the content of TaxUtil.java:

package com.devspeedup.java.junittutorial;

public class TaxUtil {
	
	public String getIncomeCategory(double salary) {
		String category; 
		
		if (salary < 40000) {
			category = "Low";
		} else if (salary < 80000) {
			category = "Medium";
		} else {
			category = "High";
		}
		
		return category;
	}
}

2. JUnit 5 Test Classes

Below are the contents of MyCalculatorTest.java and TaxUtilTest.java files:

Below is the content of MyCalculatorTest.java:

package com.devspeedup.java.junittutorial;

import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

public class MyCalculatorTest {
	
	static MyCalculator cal;
	
	@BeforeAll 
	public static void setup() {
		cal = new MyCalculator();
	}
	
	@Test
	public void addTest() {
		assertEquals(cal.add(1, 2), 3);
	}
	
	@Test
	public void substractTest() {
		assertEquals(cal.substract(1, 2), -1);
	}
}

Below is the content of TaxUtilTest.java:

package com.devspeedup.java.junittutorial;

import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.Test;

public class TaxUtilTest {
	
	@Test
	public void getIncomeCategoryTest() {

		TaxUtil util = new TaxUtil();
		
		assertEquals(util.getIncomeCategory(39000), "Low");
		assertEquals(util.getIncomeCategory(40000), "Medium");
		assertEquals(util.getIncomeCategory(80000), "High");
	}
}

3. JUnit 5 Test Suite

Below is the content of TestAll.java files:

package com.devspeedup.java.junittutorial;

import org.junit.platform.suite.api.SelectClasses;
import org.junit.platform.suite.api.Suite;

@Suite
@SelectClasses({
	MyCalculatorTest.class, 
	TaxUtilTest.class
})

public class TestAll {

}

4. Run JUnit 5 Test

  • To run an individual Test Class, in Package Explorer, right click on the class file name -> Run As -> JUnit Test
  • To run an all Test Classes, in Package Explorer, right click on TestAll.java -> Run As -> JUnit Test