Spring MockMvc Post Test:比较失败

时间:2018-01-29 01:13:01

标签: spring mocking mockito

我正试图用mockito

对这个方法进行Post测试
 @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String addBookPost(@ModelAttribute("book") Book book, HttpServletRequest request, Model model) {
        bookService.save(book);

        MultipartFile bookImage = book.getBookImage();
        try {
            byte[] bytes = bookImage.getBytes();
            String name = book.getId() + ".png";
            BufferedOutputStream stream = new BufferedOutputStream(
                    new FileOutputStream(new File("src/main/resources/static/image/book/" + name)));
            stream.write(bytes);
            stream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

到目前为止,我已经在下面做了这个,但是我的结果显示我有两个不同的对象保存实例,那就是我保存的书,并且期待的不是我得到的书。

@Test
    public void addBookClicked() throws Exception {
            Book book1 = new Book();
       // when(bookService.save(anyObject())).thenReturn(anyObject());

        mockMvc.perform(post("/book/add").with(user("admin").password("admin").roles("USER", "ADMIN"))

                .accept(MediaType.TEXT_HTML)
                .contentType(MediaType.TEXT_HTML))
                .andExpect(status().is3xxRedirection()).andDo(print())

                .andExpect(view().name("redirect:bookList"))
                .andReturn();
        Mockito.verify(bookService).save(book1);
    }

我可以在测试中使用try和catch块做什么,因为它在测试Null指针中也会出错 - 可能是因为我没有测试或添加图像到测试中。

错误日志

MockHttpServletResponse:
           Status = 302
    Error message = null

Argument(s) are different! Wanted:
com.valentine.service.BookService#0 bean.save(
    com.valentine.domain.Book@4acc5dff
);
-> at com.valentine.adminportal.controller.BookControllerTest.addBookClicked(BookControllerTest.java:80)
Actual invocation has different arguments:
com.valentine.service.BookService#0 bean.save(
    com.valentine.domain.Book@10c72a6f
);
-> at com.valentine.adminportal.controller.BookController.addBookPost(BookController.java:50)

Comparison Failure:  <Click to see difference>

Argument(s) are different! Wanted:
com.valentine.service.BookService#0 bean.save(
    com.valentine.domain.Book@4acc5dff
);
-> at com.valentine.adminportal.controller.BookControllerTest.addBookClicked(BookControllerTest.java:80)
Actual invocation has different arguments:
com.valentine.service.BookService#0 bean.save(
    com.valentine.domain.Book@10c72a6f
);
-> at com.valentine.adminportal.controller.BookController.addBookPost(BookController.java:50)

    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at com.valentine.adminportal.controller.BookControllerTest.addBookClicked(BookControllerTest.java:80)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.springf

1 个答案:

答案 0 :(得分:1)

addBookClicked中,您实际上并未向控制器发布book1。该测试方法中的book1实例仅在其创建时引用(1),并且(2)在其中进行验证。

您必须在book1调用的正文中传递mockMvc.perform()的序列化形式。

以下是一个例子:

mockMvc.perform(post("/book/add")
    .with(user("admin").password("admin").roles("USER", "ADMIN"))
    .accept(MediaType.TEXT_HTML)
    .content(objectMapper.writeValueAsString(book1))
    .contentType(MediaType.TEXT_HTML))
    .andExpect(status().is3xxRedirection()).andDo(print())
    .andExpect(view().name("redirect:bookList"))
    .andReturn();

此示例中的objectMapper是Jackson ObjectMapper的一个实例,其职责是将book1实例序列化为JSON以包含在请求正文中。