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

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

What is an In Memory Database?

In this article, we understand what the term "In-Memory Database" actually means. We see what scenarios they can be used, and why they are important.

What is an Embedded Server?

In this article, we focus in exploring what an embedded server is, and how they help make application deployment simpler.

Java Tools and Frameworks - Introduction To Maven

In this article, we experience a brief introduction to Maven, and will see how it helps in managing your project dependencies.

Five Tools To Learn as a Java Developer

In this article, we introduce you to five great tools that we recommend every Java Developer to learn.

Five Languages To Learn as a Java Programmer

As a programmer, you want to explore new things. Learning a new language gives you a different perspective when solving problems. What are the 5 languages that a Java developer should explore?

Five Great Frameworks To Try for Java Programmers

As a programmer you want to explore new languages and frameworks. What would be the best frameworks to explore in 2019 for Java Programmers?

Unit Testing Best Practices - with Java and Junit Examples

Unit Testing is often underrated. As far as I am concerned, having good unit tests seperates good projects from bad. In this article, let's look at unit testing best practices in depth. We use examples from Java and JUnit to illustrate the concepts. However, the best practices are applicable irrespective of the programming language used.

Automation Testing in Microservices - Five Types Of Automation tests

Automation tests are a very important requirement to have highly successful microservice architectures. In order to take things live on a frequent basis, it is imperative to have great automation tests. In this article, we talk of the five kinds of automation tests that you can write, for your microservices.