Mock versus Implementation. How to share both approaches in a single Test class ?
Posted
by Arthur Ronald F D Garcia
on Stack Overflow
See other posts from Stack Overflow
or by Arthur Ronald F D Garcia
Published on 2010-03-17T20:50:31Z
Indexed on
2010/03/17
21:01 UTC
Read the original article
Hit count: 505
Hi,
See the following Mock Test by using Spring/Spring-MVC
public class OrderTest {
// SimpleFormController
private OrderController controller;
private OrderService service;
private MockHttpServletRequest request;
@BeforeMethod
public void setUp() {
request = new MockHttpServletRequest();
request.setMethod("POST");
Integer orderNumber = 421;
Order order = new Order(orderNumber);
// Set up a Mock service
service = createMock(OrderService.class);
service.save(order);
replay(service);
controller = new OrderController();
controller.setService(service);
controller.setValidator(new OrderValidator());
request.addParameter("orderNumber", String.valueOf(orderNumber));
}
@Test
public void successSave() {
controller.handleRequest(request, new MockHttpServletResponse());
// Our OrderService has been called by our controller
verify(service);
}
@Test
public void failureSave() {
// Ops... our orderNumber is required
request.removeAllParameters();
ModelAndView mav = controller.handleRequest(request, new MockHttpServletResponse());
BindingResult bindException = (BindingResult) mav.getModel().get(BindingResult.MODEL_KEY_PREFIX + "command");
assertEquals("Our Validator has thrown one FieldError", bindException.getAllErrors(), 1);
}
}
As you can see, i do as proposed by Triple A pattern
- Arrange (setUp method)
- Act (controller.handleRequest)
- Assert (verify and assertEquals)
But i would like to test both Mock and Implementation class (OrderService) by using this single Test class. So in order to retrieve my Implementation, i re-write my class as follows
@ContextConfiguration(locations="/app.xml")
public class OrderTest extends AbstractTestNGSpringContextTests {
}
So how should i write my single test to Arrange both Mock and Implementation OrderService without change my Test method (sucessSave and failureSave)
I am using TestNG, but you can show in JUnit if you want
regards,
© Stack Overflow or respective owner