jeudi 29 janvier 2015

SpringMVC Unit testing - Service method is not called


Vote count:

0




When I run unit test on the controller by mocking the service bean, it looks like the service method is not called at all. Is this expected behvaior or am I missing something?


SearchController.java



@Controller
public class SearchController {

@Autowired
SearchService searchService;

@RequestMapping(value="/search", method=RequestMethod.GET)
public String showSearchPage(Model model){

model.addAttribute("list", searchService.findAll());

return "search";
}

}


SearchControllerTest.java



@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration("file:src/main/webapp/WEB-INF/springapp-servlet.xml")
public class SearchControllerTest {

@Autowired
private WebApplicationContext webAppContext;

private MockMvc mockMvc;

private SearchService searchServiceMock;

@Before
public void setUp(){
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webAppContext).build();

this.searchServiceMock = Mockito.mock(SearchServiceImpl.class);
}

@Test
public void testShowSearchPage() throws Exception{

when(searchServiceMock.findAll())
.thenReturn(Arrays.asList("rohith", "kodakandla", "kumar"));

this.mockMvc.perform(get("/search.do"))
.andExpect(status().isOk())
.andExpect(view().name("search"))
.andExpect(forwardedUrl("/WEB-INF/jsp/search.jsp"))
.andExpect(model().attribute("list", hasSize(3)));

verify(searchServiceMock, times(1)).findAll(); //this test is failing

verifyNoMoreInteractions(searchServiceMock);
}
}


When I run the test, it seems like findAll() method isn't getting called and it is throwing exception. "Wanted but not invoked searchServiceImpl.findAll()"


What mistake am I making here?



asked 57 secs ago







SpringMVC Unit testing - Service method is not called

Aucun commentaire:

Enregistrer un commentaire