Java.lang.NullPointerException出了什么问题

时间:2017-10-08 20:14:15

标签: spring mocking

它表示此方法中的错误是空指针异常

   @Test
     public void showBookListPage() throws Exception {

         List<Book> expectedBookList =  bookService.findAll();
                 BookService bookService = mock(BookService.class);

            when( bookService.findAll()).thenReturn(expectedBookList);

         BookController bookController = new BookController(bookService);
         MockMvc mockMvc = standaloneSetup(bookController).build();

         mockMvc.perform(get(" /book/bookList"))
         .andExpect(view().name("bookList"))
         .andExpect(model().attributeExists("bookList"))
         .andExpect(model().attribute("bookList", hasItems(expectedBookList.toArray())));
     }
}

除此之外,一切似乎都是正确的

这是我在致电

之前先嘲笑图书服务后得到的错误
java.lang.IllegalStateException: missing behavior definition for the preceding method call:
BookService.findAll()
Usage is: expect(a.foo()).andXXX()

    at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:42)
    at org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:94)
    at com.sun.proxy.$Proxy134.findAll(Unknown Source)
    at com.admintest.controller.BookControllerTest.showBookListPage(BookControllerTest.java:101)
    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.springf

这是我对测试方法的编辑      @测试         public void showBookListPage()抛出异常{

        BookService bookService = mock(BookService.class);
        List<Book> expectedBookList = bookService.findAll();
        when(bookService.findAll()).thenReturn(expectedBookList);

        BookController bookController = new BookController(bookService);
        MockMvc mockMvc = standaloneSetup(bookController).build();

        mockMvc.perform(get(" /book/bookList"))
                .andExpect(view().name("bookList"))
                .andExpect(model().attributeExists("bookList"))
                .andExpect(model().attribute("bookList", hasItems(expectedBookList.toArray())));
}

顺便说一句,这是控制器

 @RequestMapping("/bookList")
    public String bookList(Model model) {
        List<Book> bookList = bookService.findAll();
        model.addAttribute("bookList", bookList);
        return "bookList";

    }

1 个答案:

答案 0 :(得分:0)

在使用之前,您必须先模拟bookService。不是在使用之后。那么在@BeforeMethod

中模拟bookService