模拟测试不正确,没有显示错误,但没有给出准确的结果,为什么?

时间:2017-10-05 23:27:03

标签: spring

 This is the controller class

@RequestMapping(value="/remove", method=RequestMethod.POST)
    public String remove(
            @ModelAttribute("id") String id, Model model
    ) {
        bookService.removeOne(Long.parseLong(id.substring(8)));
        List<Book> bookList = bookService.findAll();
        model.addAttribute("bookList", bookList);

        return "redirect:/book/bookList";
    }

这是控制器测试

    @Test
    public void bookRemoveTest() throws Exception {
        securityService.autologin("admin", "admin");
        Book book = new Book();
        book.setId(2L);
        book.setTitle("brekit");
        bookService.findOne(2L);
        mockMvc.perform(
                post("/remove/2")
                        .accept(MediaType.APPLICATION_JSON)
                        .contentType(MediaType.APPLICATION_JSON)
        ).andDo(print())
                .andReturn();
    }

结果没有错误但是当我更改URL上的值时它仍然显示正确的测试,它假设删除了所述ID,任何建议人员?

我也试过这个

 @Test
    public void bookRemoveTest() throws Exception {
        securityService.autologin("admin", "admin");
        List<Book> bookList = bookService.findAll();
        Book book = new Book();
        book.setId(2L);
        book.setTitle("brekit");
        bookService.findOne(2L);
        MvcResult result = mockMvc
                .perform(post("/remove/2")
                        .accept(MediaType.APPLICATION_JSON)
                        .contentType(MediaType.APPLICATION_JSON))
                        .andExpect(status().isOk())
                        .andReturn();

        String controllerResult = result.getResponse().getContentAsString();
        assertEquals(null, controllerResult);
    }

我得到同样的错误 - 断言错误?我对此有何建议?

1 个答案:

答案 0 :(得分:0)

您没有检查返回值(aka:assertXXX)或http代码。尝试类似的东西:

   MvcResult result = mockMvc
      .perform(post("/remove/2")
      .accept(MediaType.APPLICATION_JSON)
      .contentType(MediaType.APPLICATION_JSON)
      .andExpect(status().isOk())
      .andReturn();

请注意和Expect(status()。isOk())。与200不同的所有内容都会产生错误。

然后,您可以检查将结果解码为业务对象的结果:

String controllerResult = result.getResponse().getContentAsString()
assertEquals(expected, controllerResult)