I wanted to test my controllers, and I have hard time with mocking objects. I have very simple method like this.
@RequestMapping(value = "/places", method = RequestMethod.GET)
public String showPlacesByQuery(Model model, @RequestParam(value = "q", required = false) String query) {
Location location = geolocationParser.getCoords(query); //this line cause NPE
List placesList = placeService.findPublicPlaces(location, 0);
model.addAttribute("query", query);
model.addAttribute("placesList", placesList);
return "places/list";
}
I wrote test and I'm getting NullPointerException
. I think the cause is that geolocationParser.getCoordS(query)
returns null
? or something is wrong with whole assignment Location location = geolocationParser.getCoords(query);
@Mock
GeolocationParser geolocationParser;
@Mock
PlaceService placeService;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
@Test
public void testShowPlacesByQuery() throws Exception {
String query = "SomeQuery";
PlaceController placeController = new PlaceController();
Location location = mock(Location.class);
location.setCity("someString");
location.setLatitude("54.2323");
location.setLongitude("18.2323");
when(geolocationParser.getCoords(Mockito.anyString())).thenReturn(location);
List<Place> expectedPlaces = asList(new Place(), new Place());
when(placeService.findPublicPlaces(location, 0)).thenReturn(expectedPlaces);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(placeController).build();
mockMvc.perform(get("/places").param("q", query))
.andDo(print())
.andExpect(status().isOk())
.andExpect(view().name("places/list"));
}
I spend hours to make it work, on different ways, with no results.