Reputation: 2094
It says error in this method a null pointer Exception
@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())));
}
}
Other than that everything seems to be correct
This is the error I got after mocking the book service first before call
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
And this is my edit to the test method @Test public void showBookListPage() throws Exception {
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())));
}
And by the way this is the controller
@RequestMapping("/bookList")
public String bookList(Model model) {
List<Book> bookList = bookService.findAll();
model.addAttribute("bookList", bookList);
return "bookList";
}
Upvotes: 0
Views: 724
Reputation: 16
You have to mock the bookService before using it. Not after it's usage. So do the mocking of bookService in @BeforeMethod
Upvotes: 0