Best Java Unit Testing Frameworks - With Examples of JUnit, Mockito and More...


Unit Testing is an important skill for programmers. What are the frameworks you can use to write great unit tests in the Java World?

This is second article in a series of 4 articles on Automation Testing in Microservices

You will learn

  • What are best java unit testing frameworks?
  • What is JUnit? How do you use JUnit for unit testing?
  • What is Mockito?
  • What is Mocking?
  • How do you write unit tests with Junit, Mockito, AssertJ and other frameworks?
  • What are the best java unit testing frameworks for writing great asserts?

Free Courses - Learn in 10 Steps

The Base Unit Testing Framework - JUnit / TestNG

Whenever you write a unit test, you execute some code, and then check its output. You need a basic framework in place to run a large number of tests in a similar manner.


The JUnit framework provides the basic framework that allows you to specify the test that you want to run, along with its inputs, and the result that comes out of it.

Have a look at the following test:

	public truncateAInFirst2Positions_AinFirstPosition() {
		assertEquals("CD", helper.truncateAInFirstPosition("ACD"));

Notice the annotation @Test used the decorate the test. The name of the test is descriptive, and demonstrates the intent of the test. JUnit provides different kinds of assertion methods to check the result of the code executed within a test. These include assertEquals(), assertTrue() and assertFalse().

Now have a look at this one, that tests a negative scenario:

	public testAreFirstAndLastTwoCharactersTheSame_BasicNegativeScenario() {

JUnit also supports something called parameterized tests.


TestNG is a good alternative to JUnit to write unit tests, that makes it easy to write customized tests. Suppose you have the test data needed to execute your suites in a spreadsheet or an XML document. TestNG makes it easy to get the data for tests to be written around them.

At a high level, JUnit and TestNG are frameworks that enable you to write tests and check results. If a test succeeds, you see a green bar. Else, a red bar.

Mocking Frameworks - Mockito and EasyMock

When writing unit tests, it is often required to mock or stub dependencies.

Mocking is preferred to stubbing. There are couple of great options for mocking in the java world - Mockito and EasyMock.


Have a look at the following example:

	public class SomeBusinessImpl {
		private DataService dataService;
		//Constructor - public SomeBusinessImpl(DataService dataService) { //... }

		int findTheGreatestFromAllData() {
			int[] data = dataService.retrieveAllData();
			int greatest = Integer.MIN_VALUE;
			for (int value : data) {
				if(value > greatest)
					greatest = value;
			return greatest;

The value returned by the findTheGreatestFromAllData() depends on the data that comes back from the data service.

To be able to write a good unit test for this method, you need to mock this dependency out.

Have a look at the following test for the class:

	public void testFindTheGreatestFromAllData() {
		DataService dataServiceMock = mock(DataService.class);
			.thenReturn(new int[] {24, 15, 3});

		SomeBusinessImpl businessImpl = new SomeBusinessImpl(dataServiceMock);
		int result = businessImpl.returnTheGreatestFromAllData();
		assertEquals(24, result);

Mockito make it easy to mock the DataService. Here, we use its mock() method to mock the DataService, and inject the mock into the SomeBusinessImpl class.

Mockito also provides great annotations to inject mocks automatically.

	public class SomeBusinessMockAnnotationsTest {
		DataService dataServiceMock;

		SomeBusinessImpl businessImpl;

		public void testFindTheGreatesFromAllData() {
				.thenReturn(new int[] {24, 15, 3});
			assertEquals(24, businessImpl.findTheGreatestFromAllData());

Annotations such as @Mock and @InjectMocks take care of what their names suggest, thereby making the test code smaller, and more readable.


EasyMock is also a mocking framework that can be effectively used in unit tests. It is a popular alternative to Mockito.

Mocking complex scenarios - Use PowerMock

Framworks such as Mockito allow you to insert mocks only when the code design is good. When the design is not so good, PowerMock comes to your rescue.

Powermock is useful when you want to mock static methods, constructors and private methods.

Have a look at the following code:

	interface Dependency {
		List<Integer> retrieveAllStats();

	public class SystemUnderTest {
		private Dependency dependency;

		public int methodUsingAnArrayListConstructor() {
			ArrayList list = new ArrayList();
			return list.size();

		public int methodCallingAStaticMethod() {
			//private methodUnderTest calls static method SomeClass.staticMethod

			List<Integer> stats = dependency.retrieveAllStats();
			long sum = 0;
			for(int stat : stats) {
				sum += stat;
			return UtilityClass.staticMethod(sum);

		private long privateMethodUnderTest() {
			List<Integer> stats = dependency.retrieveAllStats();
			long sum = 0;
			for(int stat : stats) {
				sum += stat;

			return sum;

Here, SomeClass.staticMethod is a static method that is defined. Therefore, we have a need to mock it out. We need to test the method methodCallingAStaticMethod() after this mock. Have a look at the following test code:

	public class PowerMockitoMockingStaticMethodTest {
		Dependency dependencyMock;
		SystemUnderTest systemUnderTest;

		public void powerMockito_MockingAStaticMethodCall() {
			when(dependencyMock.retrieveAllStats()).thenReturn(Arrays.asList({1, 2, 3}));

			assertEquals(150, systemUnderTest.methodCallingAStaticMethod);

			//Verify the specific method call

			//First, call PowerMockito.verifyStatic()
			//Second, call the method to be verified

			UtilityClass.staticMethod(1 + 2 + 3);

			//verify exact number of calls


Here we have written code that allows us to mock out a static method.

It is also possible to mock a constructor:

	public class PowerMockitoMockingConstructorTest {
		private static final int SOME_DUMMY_SIZE = 100;

		Dependency dependencyMock;
		SystemUnderTest systemUnderTest;

		public void powerMockito_MockingAConstructor throws Exception {
			ArrayList<String> mockList = mock(ArrayList.class);


			int size = systemUnderTest.methodUsingAnArrayListConstructor();
			assertEquals(SOME_DUMMY_SIZE, size);

When the constructor is called, the mockList is returned instead.

PowerMock can also be used to mock private methods:

	public class PowerMockitoMockingPrivateMethodTest {

		Dependency dependencyMock;
		SystemUnderTest systemUnderTest;

		public void powerMockito_CallingAPrivateMethod throws Exception {
			when(dependencyMock.retrieveAllStats()).thenReturn(Arrays.asList({1, 2, 3}));

			long value = (Long) WhiteBox.invokeMethod(systemUnderTest,
			assertEquals(6, value);

Note that you cannot directly invoke a private method from test code. We are using the functionality of a class named WhiteBox, to which we pass the string name of the private method.

Writing great asserts using AssertJ / Hamcrest

Whenever you write tests, you want to have great assertions.


Have a look at the folowing code:

	public class AssertJTest {
		public void learning() {
			List<Integers> numbers = Arrays.asList({12, 15, 45});

									.contains(12, 15)
									.allMatch(x -> x > 10)
									.allMatch(x -> x < 100)
									.noneMatch(x -> x < 0);

numbers is a list of integers that contains 3 values as shown. AssertJ provides the method assertThat(), which allows you to chain together multiple assertions.

Interestingly, you can see that the method allMatch() accepts a lambda expression to test the truth value of a predicate. The call allMatch(x -> x > 10) checks whether all the integers within numbers match the predicate of being greater than 10.

assertThat() also works with strings, and works well especially with alphabetical text. The code is there for you to see.


Hamcrest provides an alternative to AssertJ to write great asserts.

	public class HamcrestMatchersTest {
		public void learning() {
			List<Integer> numbers = Arrays.asList({12, 15, 45});

			assertThat(numbers, hasSize(3));
			assertThat(numbers, hasItems(12, 15));
			assertThat(numbers, everyItem(greaterThan(10)));
			assertThat(numbers, everyItem(lessThan(100)));

			assertThat("", isEmptyString());
			assertThat("ABCDE", containsString("BCD"));
			assertThat("ABCDE", startsWith("ABC"));
			assertThat("ABCDE", endsWith("CDE"));

Using Spring Unit

Typical applications have multiple layers and you want to write unit tests for different layers - web, business and data.

Here are some of the recommended options:

  • Web layer - Spring MockMVC
  • Data layer - DataJpaTest
  • Business layer - Mockito based test preferably without launching a Spring Context

Unit Tests For The Web Layer

Have a look at the following code:

	public class ItemControllerTest {
		private MockMvc mockMvc;

		private ItemBusinessService businessService;

		public void dummyItem_basic throws Exception {
			RequestBuilder request = MockMvcRequestBuilders

			MvcResult result = mockMvc.perform(request)
											.json("{\"id\":1, \"name\":\"Ball\"
													, \"price\":10, \"quantity\":5}"))

		//JSONAssert.assertEquals(expected, result.getResponse.getContentAsString(), flase);

This unit test uses the Spring Unit framework, and the Spring MockMVC framework.

We are launching a Spring context and wiring ItemController to use a mock for ItemBusinessService.

Spring MockMVC framework makes it easy to perform REST API requests. In the code above we are using it to execute a REST API, and then setting certain expectations of the result:

  • The URL is /dummy-item
  • The accepted content type is application+json
  • After the request has been sent, check that the response status is “OK”, and the content is a JSON object with certain data

It is also possible for us to mock the business service:

	public void retrieveAllItems_basic() throws Exception {
					Arrays.asList(new Item(2, "Item2", 10, 10)
									, new Item(3, "Item3", 20, 20)));

		RequestBuilder request = MockMvcRequestBuilders

		MvcResult result = mockMvc.perform(request)
											.json("[{\"id\":3, \"name\":\"Item3\"
													, \"price\":20}]"))
													,{\"id\":2, \"name\":\"Item2\"
													, \"price\":10}]")

When retrieveAllItems() is called on businessService, it is made to return the fixed list of items shown. Once again, we execute a request to a different URL, and when the response comes in, the content is verified to be the proper JSON type, with the expected data.

Unit Tests For The Data Layer

DataJpaTest can be used during unit testing of the data layer in an Spring Based enterprise application. DataJpaTest uses an in-memory database for the unit test, by default.

	public class ItemRepositoryTest {
		private ItemRepository repository;
		public void testFindAll() {
			List<Item> items = repository.findAll();
			assertEquals(3, items.size());
		public void testFindOne() {
			Item item = repository.findById(10001).get();
			assertEquals("Item1", item.getName());

Asserting JSON Responses - JSONAssert / JSONPath

Almost all REST API use JSON. How do you assert JSON Content?

Using JSONAssert

Have a look at the following test code:

image info

actualResponse is the content that is returned by a service.

JSONAssert allows us to check specific parts of the request that we are interested in.

  • Within the test jsonAssert_StrictFalse(), we are only concerned with the id, name and price, ignoring the quantity.
  • You can also write a test to check without escape characters, as we have done with jsonAssert_WithoutEscapeCharacters(). This is much easier on the eye, and can be used to compare with an actual response that contains escape characters. This mode of comparing responses is called Strict False.

You can also do assertions in Strict mode, where you compare all the fields, and in the actual format they are in. That is what we have done with jsonAssert_StrictFalse_ExactMatchExceptForSpaces().

Using JSONPath

Alternative approach in asserting JSONs is the JSONPath framework. You might want to check for specific aspects of the response, such as three items in the response.

image info

Just as XPath is used to query XML, JSONPath is used to query JSON.

  • The expression $.length() returns the number of elements. An assertion can then be used on that returned value.
  • You can check for all the id fields with $ and compare them with a list of pre-fixed values.
  • You can extract slices of the element list that is in the resonse, such as the first element ($.[1]), or the first 2 elements ($.[0:2]).
  • You can query the reponse to check if a particular field is present : $.[?( == 'Eraser')] or $.[?(@.quantity == 5)].

Do check out our video on the same topic:

image info


In this article, we looked at a wide variety of unit testing fraemworks present in the Java world. We started with the basic unit testing framework JUnit, and its alternative, TestNG. We looked at how we can do mocking with Mockito and its alternative, EasyMock. We then had a look at Powermock, which is useful when mocking static methods, private methods and constructors.

We then had a feel of powerful assertion frameworks such as AsserJ and Hamcrest. Spring Unit framework provides MockMVC as the mocking framework for the web layer and DataJPATest for the data layer. Finally, we explored JSONAssert and JSONPath, used to assert JSON responses in a unit test.

Best Selling Udemy Courses

Image Image Image Image Image Image Image Image Image

Join 450,000 Learners and 30+ Amazing Courses

350,000 Learners are learning everyday with our Best Selling Courses : Spring Boot Microservices, Spring, Spring Boot, Web Services, Hibernate, Full Stack React, Full Stack Angular, Python, Spring Interview Guide, Java Interview, Java Functional Programming, AWS, Docker, Kubernetes, PCF, AWS Fargate and Azure

Do not know where to start your learning journey? Check out our amazing learning paths:
Learning Path 01 - Spring and Spring Boot Web Applications and API Developer,
Learning Path 02 - Full Stack Developer with Spring Boot, React & Angular,
Learning Path 03 - Cloud Microservices Developer with Docker and Kubernetes,
Learning Path 04 - Learn Cloud with Spring Boot, AWS, Azure and PCF and
Learning Path 05 - Learn AWS with Microservices, Docker and Kubernetes



Related Posts

Writing Integration Tests for Rest Services with Spring Boot

Setting up a basic REST Service with Spring Boot is a cake walk. We will go one step further and add great integration tests!

Integrating Spring Boot and Spring JDBC with H2 and Starter JDBC

Learn using Spring Boot Starter JDBC to connect Spring Boot to H2 (in memory database) using Spring JDBC. You will create a simple project with Spring Boot. You will add code to the project to connect to a database using Spring JDBC. You will learn to implement the basic CRUD methods.

JUnit Tutorial for Beginners in 5 Steps

JUnit Tutorial for Beginners in 5 Steps. Setting up a basic JUnit example and understanding the basics of junit.

JPA and Hibernate Tutorial For Beginners - 10 Steps with Spring Boot and H2

JPA and Hibernate in 10 Steps with H2 - Setting up a basic project example with Spring Boot and in memory database H2. Its a cake walk.

Spring Boot Tutorial For Beginners in 10 Steps

Introduction to Spring Boot in 10 Steps. Learn the basics of Spring Boot setting up a basic project example with Spring Boot.

Spring Framework Tutorial for Beginners - Your First 10 Steps

Learn the basics of Spring Framework setting up a very simple example.

JPA and Hibernate Tutorial using Spring Boot Data JPA

Complete journey starting from JDBC to JPA to Spring Data JPA using an example with Spring Boot Data JPA starter project. We use Hibernate as the JPA Implementation.

Creating a Web Application with Spring Boot with JSP

Setting up a basic web application with Spring Boot is a cake walk. We will create a simple web application using Spring Initializr and add JSP features to it.

What is Spring Boot Auto Configuration?

Auto Configuration is the most important feature in Spring Boot. In this tutorial, we will learn important concepts about Auto Configuration with a couple of examples.

Unit Testing Rest Services with Spring Boot and JUnit

Setting up a Basic REST Service with Spring Boot is a cake walk. We will go one step further and add great unit tests to our RESTful Service.