'Spring Controller Test - object in controller is null
I try to test a controller and have a problem with an object City c = cityService.findByID(city); It is always null when I run the test. If I run the program and not the test it works as it should.
City c shouldn't be null because it is an object which should be fetched from DB by city id of last selected city(option from dropdown list) and I pass the city id here: .param("city", String.valueOf(306)).
void selectCityTest() throws Exception { //post
Integer voivodeship = 10;
Integer city = 306;
List<City> cities = cityService.getAllCitiesByVoivodeship(voivodeship);
mockMvc.perform(MockMvcRequestBuilders.post("/select_city")
.contentType(MediaType.APPLICATION_JSON)
.param("city", String.valueOf(306))
.content(new Gson().toJson(cities)))
.andExpect(status().isOk());
}
Controller.java
@RequestMapping(value = "/select_city", method = RequestMethod.POST)
public String selectCity(Integer city, Model model) {
City c = cityService.findByID(city);
List<City> cities = cityService.getAllCitiesByVoivodeship(c.getVoivodeship().getId());
model.addAttribute("cities", cities);
model.addAttribute("city_selected", city);
return "taxoffice";
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
