Answering with 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.
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?