About Alex Soto

Answering with Mockito

When you are writing unit tests, you must keep in mind to not have dependencies to external components. To avoid this we use mock frameworks which for me the easiest one to use is Mockito.
In this post we are going to see an ‘advanced’ technique used in Mockito to return same argument instance on a mocked method using Answer interface.

Suppose we are writing unit tests for class which manages Person and Job classes and as operation it uses a DAO class for inserting the relationship class (M:N) between Person and Job called PersonJob.
For example class under test will look something like:

 public PersonJob createPersonJob(Person person, Job job) {
 
  ..  some job .. 
  PersonJob personJob = new PersonJob(person, job);
  return  this.personJobDao.create(personJob);
 
 }

So in this case it seems obvious that you need to mock personJobDao.
Let’s create the mock and record the interaction:

 public class WhenAJobIsAssignedToPerson {
 
  @Test
  public void relationship_should_be_made_persistent() {
 
   PersonJobDao personJobDao = mock(PersonJobDao.class);
   when(personJobDao.create(any(PersonJob.class))).thenReturn(???)
 
   PersonJobManager personJobManager = new PersonJobManager();
   personJobManager.setPersonJobDao(personJobDao);
 
   Person person = new Person();
   Job job = new Job();
   PersonJob personJob = personJobManager.createPersonJob(person, job);
 
   assertThat(personJob.getPerson(), is(person));
   assertThat(personJob.getJob(), is(job));
 
  }
 
 }

Yes as you can see you don’t know what to return, because instance is created by class under test and in the test method you don’t know which instance is created by createPersonJob method. To solve this problem, you need to use thenAnswer instead of thenReturn method:

 public class WhenAJobIsAssignedToPerson {
 
  @Test
  public void relationship_should_be_made_persistent() {
 
   PersonJobDao personJobDao = mock(PersonJobDao.class);
   when(personJobDao.create(any(PersonJob.class))).thenAnswer(new Answer<PersonJob>() {
 
    public PersonJob answer(InvocationOnMock invocation)
      throws Throwable {
     return (PersonJob) invocation.getArguments()[0];
    }
   });
 
   PersonJobManager personJobManager = new PersonJobManager();
   personJobManager.setPersonJobDao(personJobDao);
 
   Person person = new Person();
   Job job = new Job();
   PersonJob personJob = personJobManager.createPersonJob(person, job);
 
   assertThat(personJob.getPerson(), is(person));
   assertThat(personJob.getJob(), is(job));
 
  }
 
 }

Note that Answer interface requires you to implement answer method, which in our case simply returns the first argument ( PersonJob instance) of personJobDao. create method.

Now we can write assertions in peace without worrying about returned instance.

Reference: Answering with Mockito from our JCG partner Alex Soto at the One Jar To Rule Them All blog.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

One Response to "Answering with Mockito"

  1. Marcin Grzejszczak says:

    Hi! Nice post :) Wouldn’t it be easier to replace the construction of the PersonJob by new operator with a factory whose behavior you could mock?

Leave a Reply


four − 2 =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close