private MessageSource messageSource;
@Test
public void testCreate() {
final Contact newContact = new Contact();
newContact.setId(999l);
newContact.setFirstName("Rod");
newContact.setFirstName("Johnson");
contactService = mock(ContactService.class);
when(contactService.save(newContact)).thenAnswer(new Answer<Contact>() {
public Contact answer(InvocationOnMock invocation) throws Throwable {
contacts.add(newContact);
return newContact;
}
});
messageSource = mock(MessageSource.class);
when(messageSource.getMessage("contact_save_success", new Object[]{},
Locale.ENGLISH)).thenReturn("success");
ContactController contactController = new ContactController();
ReflectionTestUtils.setField(contactController, "contactService",
contactService);
ReflectionTestUtils.setField(contactController, "messageSource",
messageSource);
BindingResult bindingResult = new BeanPropertyBindingResult(
newContact, "contact");
ExtendedModelMap uiModel = new ExtendedModelMap();
HttpServletRequest httpServletRequest = new MockHttpServletRequest();
RedirectAttributes redirectAttributes =
new RedirectAttributesModelMap();
Locale locale = Locale.ENGLISH;
String result = contactController.create(newContact, bindingResult,
uiModel, httpServletRequest, redirectAttributes, locale, null);
assertNotNull(result);
assertEquals("redirect:/contacts/999", result);
assertEquals(2, contacts.size());
}
}
In Listing 19-4, the ContactService.save() method is mocked to simulate the addition of a new
Contact object in the list of contacts. Note the use of the org.mockito.stubbing.Answer<T> interface,
which mocks the method with the expected logic and returns a value.
Moreover, a mocked instance of the MessageSource interface is mocked with Mockito. Then an
instance of ContactController class is constructed, and its dependencies to ContactService and
MessageSource are set with the mocked implementation. In addition, besides ExtendedModelMap,
instances of RedirectAttributes and HttpServletRequest are constructed. For the HttpServletRequest
interface, note the use of the MockHttpServletRequest class, which is Spring's mocked implementation.
There are also a number of mock classes within the org.springframework.mock.web package to help
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home