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.

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

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


five × = 25



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
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.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books