Question
I have tried the documentation on the jmock site and I'm simply lost. It appears that it's great documentation for someone that already knows how to use it. I'm not one of those. I'm looking for one of those. :)
I have a services layer that all front ends to my app communicate with. The services layer uses the DAOs to communicate with the database and return my model objects. I'd like to use Jmock for those DAOs so that there's no trips to a database.
So, I have PersonServiceImpl that implements PersonService and PersonHibernateDAO that implements PersonDAO in hibernate. Example person service follows.
public class PersonServiceImpl implements PersonService{
public void changeName(int personId, String firstName, String lastName){
person = getPersonDAO.getPerson(int personId);
person.setFirstName(firstName);
person.setLastName(lastName);
getPersonDAO.update(person);
}
}
How do I use jmock to unit test my person service?
Solution
I think this is what should work.
public class MyTestClass{
Mockery context = new Mockery();
private PersonServiceImpl personService;
private PersonDAO dao;
private Person person;
@Before
public void setup(){
person = new Person();
// set up mock to return person object
dao = context.mock(PersonDAO.class);
oneOf (dao).getPerson(5); will(returnValue(person));
// create class under test with mock
personService = new PersonServiceImpl(dao);
}
@Test
public void myTest(){
// expectations
context.checking(new Expectations() {{
oneOf (dao).update(person);
}});
// test
psersonService.changeName(....);
// verify
context.assertIsSatisfied();
}
}
Personally, I think mockito is easier...
public class MyTestClass{
private PersonServiceImpl personService;
private PersonDAO dao;
private Person person;
private ArgumentCaptor<Person> argCaptor;
@Before
public void setup(){
person = new Person();
argCaptor = ArgumentCaptor.forClass(Person.class);
// set up mock to return person object
dao = Mockito.mock(PersonDAO.class);
when(dao.getPerson(5).thenReturn(person);
// create class under test with mock
personService = new PersonServiceImpl(dao);
}
@Test
public void myTest(){
// test
psersonService.changeName(....);
// verify
verify(dao).update(argCaptor.capture());
Person passedPerson = argCaptor.getValue();
assertThat(passedPerson.getFirstName(), equalTo(...));
}
}