Programming Basics - Unit Testing - What Is Mocking?


Mocking is an important concept that is made use of, when writing unit tests. In this article, we explore what mocking is all about, and explore some of the popular Java mocking frameworks in use.

You will learn

  • What is mocking?
  • Why is mocking important?
  • How can you use Mockito framework to mock classes in Java?
  • What are things Mockito framework good at?
  • What are features of PowerMock framework?

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

Why Do We Need Mocking?

Have a look at the following Java code:


	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;
	  }
	}

SomeBusinessImpl gets the data it needs, through a DataService, which is an external interface. findTheGreatestFromAllTheData() represents a certain business logic applied to this data.

Let’s say we want to write a unit test for SomeBusinessImpl. The basic approach is to let the code run as is, connect to the database and write test based on the data in the database.

Let’s say the data in the database has been modified by another developer. The unit test would start failing even though the code is still right.

The unit test for SomeBusinessImpl might because it has an external dependency, which is never stable. How do we write a test for SomeBusinessImpl which does not have such an external dependency?

Enter Mocking

One way out is to create a mock for DataService:


	@RunWith(MockitoJUnitRunner.class)
	public class SomeBusinessMockAnnotationsTest {
	
	  @Mock
	  DataService dataServiceMock;
	
	  @InjectMocks
	  SomeBusinessImpl businessImpl;
	
	  @Test
	  public void testFindTheGreatestFromAllData() {
	    when(dataServiceMock.retrieveAllData())
	            .thenReturn(new int[] { 24, 15, 3 });    
	    assertEquals(24, businessImpl.findTheGreatestFromAllData());
	  }

You create a mock with the DataService class, and then do what you need to with that mock.

Our mock here says: “When retrieveAllData() is called, then return the specific data new int[] { 24, 15, 3 }”. We know that if the input data is {24, 15, 3}, the value expected to be returned is 24. We write the test using this.

This makes sure that the data which is provided to SomeBusinessImpl is within the boundary of the unit test.

The code that we see above uses a popular mocking framework called Mockito. You would see that the code written is very readable, almost like plain English. Using mocks, you can mock away entire classes. Mocking also leads to stable unit tests.

Exploring Mocking Frameworks

Using Mockito With Good Design

When you have well defined classes and interfaces, unit testing with Mockito is a breeze. Mockito also provides useful annotations such as @Mock and @InjectMocks.


	@RunWith(MockitoJUnitRunner.class)
	public class SomeBusinessMockAnnotationsTest {
	
	  @Mock
	  DataService dataServiceMock;
	
	  @InjectMocks
	  SomeBusinessImpl businessImpl;
	
	  @Test
	  public void testFindTheGreatestFromAllData() {
	    when(dataServiceMock.retrieveAllData())
	            .thenReturn(new int[] { 24, 15, 3 });    
	    assertEquals(24, businessImpl.findTheGreatestFromAllData());
	  }

Using PowerMock With Poor Design

Sometimes however, your code might be designed very poorly. You could be making heavy use of static methods, and could also be using private methods. In addition, you might need to mock a constructor. In such cases, you need to use PowerMock along with Mockito.

Do check out our video on this:

image info

Summary

Mocking is a technique of unit testing a class, where we mock an external dependency in order to test our classes and methods. When unit tests are written well with mocks, they would not have any external dependencies and will not fail when external stuff changes. We looked at the Mockito framework. We also looked at the option of PowerMock for testing badly designed code.

Congratulations! You are reading an article from a series of 50+ articles on Spring, Spring Boot , Hibernate, Full Stack, Cloud and Microservices. We also have 20+ projects on our Github repository. For the complete series of 50+ articles and code examples, click here.

Join 300,000 Learners!

Learn Spring Boot in 10 Steps - FREE Course

Next Steps

Image

Image

Image Image

Image

Image

Image

Image

Image

Image

Image

Image

Image

Image

Image

Image

Related Posts

Spring Boot Tutorials for Beginners

At in28Minutes, we are creating a number of tutorials with videos, articles & courses on Spring Boot for Beginners and Experienced Developers. This resources will help you learn and gain expertise at Spring Boot.

Spring and Spring Boot Video Tutorials for Beginners

At in28Minutes, we are creating a number of tutorials with videos, articles & courses on Spring Boot for Beginners and Experienced Developers. Here's a list of video tutorials and courses for you

Software Design - Separation Of Concerns - with examples

Software architects and programmers love having Seperation of Concerns. What is it? Why is it important? Let's get started.

Object Oriented Software Design - Solid Principles - with examples

Software design is typically complex. Object oriented design takes it to the next level. There are a number of design patterns and other stuff to be aware of. Can we make things simple? What are the goals to aim for when you are doing object oriented design? SOLID Principles is a great starting point for Object Oriented Design.

Software Design - Open Closed Principle - with examples

Open Closed Principle is one of the SOLID Principles. You want your code to be easily extended. How do you achieve it with minimum fuss? Let's get started.

Software Design - What is Dependency Inversion Principle?

Dependency Inversion Principle is one of the important SOLID Principles. Dependency Inversion Principle is implemented by one of the most popular Java frameworks - Spring. What is it all about? How does it help you design good applications?

Introduction to Four Principles Of Simple Design

With agile and extreme programming, the focus is on keeping your design simple. How do you keep your design simple? How do you decide whether your code is good enough?

Software Design - Single Responsibility Principle - with examples

For me, Single Responsibility Principle is the most important design principle. What is Single Responsibility Principle? How do you use it? How does it help with making your software better? Let's get started.

REST API Best Practices - With Design Examples from Java and Spring Web Services

Designing Great REST API is important to have great microservices. How do you design your REST API? What are the best practices?

Designing REST API - What is Code First Approach?

Designing Great REST API is important to have great microservices. Code First approach focuses on generating the contract from code. Is it the best possible approach?