Skip to content

Instantly share code, notes, and snippets.

@aziz781
Created October 28, 2011 09:32
Show Gist options
  • Save aziz781/1321958 to your computer and use it in GitHub Desktop.
Save aziz781/1321958 to your computer and use it in GitHub Desktop.
The following example shows how we can test application component that has DAO (heavy weight) dependency using jmock objects and web layer (Controller) using spring mock api
@RunWith(JMock.class)
public class HomeControllerTest {
Mockery context = new JUnit4Mockery();
//mock object : ContactDAO (using JMock)
ContactDAOInterface contactDAO = context.mock(ContactDAOInterface.class);
// Spring MVC controller
HomeController cc = new HomeController();
// mock objects (using spring mock)
private MockHttpServletRequest request;
private MockHttpServletResponse response;
@Before
public void init() throws Exception
{
cc.setContactDAO(contactDAO);
// mock objects created
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
}
@Test
public void HomePage() throws Exception
{
// define expectations for mock object
context.checking(new Expectations() {{
ArrayList<ContactData> data = new ArrayList<ContactData>();
data.add(new ContactData(1,"Abdul Aziz","07525776781"));
oneOf (contactDAO).getContacts(); will(returnValue(data));
}});
// test
request.setMethod("GET");
ModelAndView mav= cc.handleRequest(request, response);
Assert.assertEquals("viewContacts", mav.getViewName());
ArrayList<ContactData> obj=(ArrayList<ContactData>)mav.getModel().get("contacts");
Assert.assertNotNull(obj);
Assert.assertEquals(1,obj.size());
Assert.assertEquals("Abdul Aziz",obj.get(0).getName());
Assert.assertEquals("07525776781",obj.get(0).getPhone());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment