我正在使用mockito来测试返回String的方法。当我运行测试时,它失败并显示错误
java.lang.AssertionError: Response content expected:<true> but was:<false>
我是Mockito的新手,我无法弄清问题是什么。有人可以帮我弄清楚我做错了什么。
我正在测试的方法:
@RequestMapping(value="/menus/update", method=RequestMethod.POST)
@ResponseBody
public String submitEditMenu(HttpServletRequest request,
HttpServletResponse response, @ModelAttribute("menu") Menu menu) {
return String.valueOf( iMenuService.updateMenu(menu));
}
测试类
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration("classpath:spring-security.xml")
public class TestMenuController{
@Mock
private HttpServletRequest request;
@Mock
private HttpServletResponse response;
@Mock
private IMenuService iMenuService;
@Mock
private WebApplicationContext weApp;
private MockMvc mockMvc;
@InjectMocks
private MenuController menuController;
@Before
public void setup() throws Exception {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(menuController).build();
}
@Test
public void testSubmitEditMenu() throws Exception {
Menu menu = new Menu.MenuBuilder()
.setMenuId(1)
.setMenuName("menu1")
.build();
when(iMenuService.updateMenu(menu)).thenReturn(true);
MvcResult result =
mockMvc.perform(MockMvcRequestBuilders.post("/menus/update")
.param("menuId", "1")
.param("menuName", "menu1"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content()
.contentType("text/plain;charset=ISO-8859-1"))
.andExpect(MockMvcResultMatchers.content().string("true"))
.andDo(MockMvcResultHandlers.print())
.andReturn();
assertNotNull(result);
}
}
回复
MockHttpServletResponse:
Status = 200
Error message = null
Headers = {Content-Type=[text/plain;charset=ISO-8859-1], Content-Length=[5]}
Content type = text/plain;charset=ISO-8859-1
Body = false
Forwarded URL = null
Redirected URL = null
Cookies = []
答案 0 :(得分:0)
模拟时使用的Menu
对象和请求后创建的Menu
对象不同。
您可以使用when(iMenuService.updateMenu(Mockito.any(Menu.class))).thenReturn(true);
进行模拟以使其正常工作。
然而,这使得从Menu
对象的属性中获得测试结果。你可以改用它;
when(iMenuService.updateMenu(Mockito.any(Menu.class))).then(invocationOnMock -> {
Menu menu = invocationOnMock.getArgumentAt(0, Menu.class);
return menu.getMenuId() == 1 && "menu1".equals(menu.getMenuName());
});
现在,当且仅当它获得id为Menu
且name = 1
menu1
对象时,模拟对象才会返回true