由于响应中的错误结果,弹簧方法的Mockito测试失败

时间:2018-06-04 06:34:34

标签: java spring junit mockito

我正在使用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 = []

1 个答案:

答案 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