Created
October 28, 2011 09:32
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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
http://j2eeroad.wordpress.com/2010/02/07/testing-using-junit-4-jmock-spring-mock/