Table of contents
1.
Introduction
2.
Stub
3.
Mockito - Stubbing a method's Return Value
3.1.
when-thenReturn
3.2.
doReturn-when
4.
Example of Stubbing
5.
Advantages of Stubbing
6.
FAQs
6.1.
What is stubbing in testing?
6.2.
What is the difference between stubbing and mocking?
6.3.
When would you want to use a stub function?
6.4.
What is a stubbing response?
6.5.
What are test drivers and stubs?
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

Stubbing Methods And Returning Default Values

Author Yukti Kumari
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Mockito is emerging as a dominant mocking framework. 

In this article, we will learn about the Stubbing Methods in Mockito and returning default values.

To make the most out of this article, you should be familiar with the basics of the Mockitio Framework. Consider reading Getting Started With Mockito for a clear understanding.

Stub

Before learning about stubbing methods, it's good to understand what a stub actually means. A stub is nothing more than a fake class that consists of preprogrammed return values. When injected into a class, it gives absolute control over the testing input.

Mockito - Stubbing a method's Return Value

Stubbing can be defined as configuring a mock and defining the actions to be taken when a specific method of the mock is invoked.

Mockito offers two methods of stubbing, namely, when-thenReturn and doReturn-when methods.

when-thenReturn

In easy words, it simply means - When this method is invoked, then do something.

thenReturn() is used to specify the return value/values when a specific method is invoked.

Consider the following snippet of code:

when(passwordEncoder.encode("1")).thenReturn("a");


The above code snippet tells that When passwordEncoder.encode(“1”) is called, return an a.

doReturn-when

It means that “Do something when this mock’s method is called with the following arguments”. 

doReturn() is used to specify the return value/values when a specific method is invoked.

Since the cause is defined at the end, in this case, it sometimes becomes difficult to read.

Consider the following snippet of code:

doReturn("a").when(passwordEncoder).encode("1");

 

The above snippet can be read as “Return a when passwordEncoder’s encode() method is called with an argument of 1.”

Example of Stubbing

In this section, you will see an example which will demonstrate how to use stubbing in mockito.

Consider the following code for the Customer class:

@Entity
public class Customer {


@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;


private String firstName;

private String lastName;

//...getters and setters redacted for brevity...


}

 

Consider the following code for the Business class:

public class CustomerReader {

@PersistenceContext
private EntityManager entityManager;

public String findFullName(Long customerID){
Customer customer = entityManager.find(Customer.class, customerID);
return customer.getFirstName() +" "+customer.getLastName();
}


}

 

The business class reads the customer data from the database through the entity manager.

Let’s think of some ways to test this class.

One of the most naive ways can be to populate a database and then run this class against it. But this isn’t practical for a real-life scenario.

So, how to test?

By removing the database dependency we can achieve this efficiently. Instead of a real database, we can stub the database connection, which will make the class to think of it as a real EntityManager but we know it is nothing but a Mockito stub.

In this way, we can have control over the return values of a database connection unlike the case of using a real database.

The unit test for testing the above class can be thus written as shown below:

public class CustomerReaderTest {


@Test
public void happyPathScenario(){
Customer sampleCustomer = new Customer();
sampleCustomer.setFirstName("Susan");
sampleCustomer.setLastName("Ivanova");

EntityManager entityManager = mock(EntityManager.class);
when(entityManager.find(Customer.class,1L)).thenReturn(sampleCustomer);

CustomerReader customerReader = new CustomerReader();
customerReader.setEntityManager(entityManager);

String fullName = customerReader.findFullName(1L);
assertEquals("Susan Ivanova",fullName);
}
}

 

Let's see step by step what is being done in the above unit test - 

  • It creates a sample customer, which is a real class and not a mock as its fast to create it.
  • It mocks the Entity Manager using a mock() static call.
  • It defines what to do when the find() method of the Entity Manager is invoked. In this case it simply returns the sample customer.
  • Next it creates a class under test CustomerReader and the mocked Entity Manager is passed to it as a dependency.
  • Then the class just class its methods.

Advantages of Stubbing

  • It does not need any external dependencies and only needs a source java code.
  • It is super fast and deterministic.
  • Avoids the need for a real database.

FAQs

What is stubbing in testing?

Stubbing, like mocking, means creating a stand-in, but a stub only mocks the behaviour, but not the entire object. This is used when your implementation only interacts with a certain behaviour of the object.

What is the difference between stubbing and mocking?

Stub: a dummy piece of code that lets the test run, but you don't care what happens to it. Mock: a dummy piece of code, that you VERIFY is called correctly as part of the test.

When would you want to use a stub function?

Stubs are used commonly as placeholders for the implementation of a known interface, where the interface is finalized/known but the implementation is not yet known/finalized. 

What is a stubbing response?

Stubbing means replacing a method, function or an entire object with a version that produces hard-coded responses.

What are test drivers and stubs?

Stubs are basically known as “called programs” and are used in the Top-down integration testing. While drivers are the “calling program” and are used in bottom-up integration testing.

Conclusion

In this article, we have extensively discussed Stubbing Methods and returning default values.

We hope that this blog has helped you enhance your knowledge regarding Stubbing Methods and if you would like to learn more, check out our articles on Capturing Arguments, Mockito AnnotationsCreating Mocks and the need of mockingTesting exceptions

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. 

Enrol in our courses and refer to the mock test and problems available.

Take a look at the interview experiences and interview bundle for placement preparations.

Do upvote our blog to help other ninjas grow. 

Happy Coding!

Live masterclass