@Test public void createOk() { // Given Model model = new ExtendedModelMap(); Entry entry = entryFactoryForTest.newEntry(); BindingResult bindingResult = mock(BindingResult.class); RedirectAttributes redirectAttributes = mock(RedirectAttributes.class); HttpServletRequest httpServletRequest = mock(HttpServletRequest.class); Entry entryCreated = new Entry(); when(entryService.create(entry)).thenReturn(entryCreated); // When String viewName = entryController.create(entry, bindingResult, model, redirectAttributes, httpServletRequest); // Then assertEquals("redirect:/entry/form/" + entry.getIdentry(), viewName); Map<String, ?> modelMap = model.asMap(); assertEquals(entryCreated, (Entry) modelMap.get("entry")); assertEquals(null, modelMap.get("mode")); assertEquals(null, modelMap.get("saveAction")); Mockito.verify(messageHelper) .addMessage(redirectAttributes, new Message(MessageType.SUCCESS, "save.ok")); }
@Test public void createException() { // Given Model model = new ExtendedModelMap(); givenPopulateModel(); RedirectAttributes redirectAttributes = mock(RedirectAttributes.class); HttpServletRequest httpServletRequest = mock(HttpServletRequest.class); BindingResult bindingResult = mock(BindingResult.class); when(bindingResult.hasErrors()).thenReturn(false); Entry entry = entryFactoryForTest.newEntry(); Exception exception = new RuntimeException("test exception"); when(entryService.create(entry)).thenThrow(exception); // When String viewName = entryController.create(entry, bindingResult, model, redirectAttributes, httpServletRequest); // Then assertEquals("entry/form", viewName); Map<String, ?> modelMap = model.asMap(); assertEquals(entry, (Entry) modelMap.get("entry")); assertEquals("create", modelMap.get("mode")); assertEquals("/entry/create", modelMap.get("saveAction")); Mockito.verify(messageHelper).addException(model, "entry.error.create", exception); @SuppressWarnings("unchecked") List<EntrytypeListItem> entrytypeListItems = (List<EntrytypeListItem>) modelMap.get("listOfEntrytypeItems"); assertEquals(2, entrytypeListItems.size()); }