0

I try to test a controller and have a problem because of a parameter. I recieve an error:

"cannot invoke "java.lang.Integer.intValue()" because "voivodeship" is null"

It shouldn't be null. because it is an id of last selected voivodeship(option from dropdown list). I think the problem is here .requestAttr("voivodeship", 10). How can i pass this parameter using mockMvc?

@Test
    public void selectVoivodeshipTest() throws Exception { //post

        Integer voivodeship = 10;
        List<Voivodeship> voivodeships = voivodeshipService.findAll();
        List<City> cities = cityService.getAllCitiesByVoivodeship(voivodeship);
        mockMvc.perform(MockMvcRequestBuilders.post("/select_voivodeship")
                        .contentType(MediaType.APPLICATION_JSON)
                        .requestAttr("voivodeship", 10)
                        .content(new Gson().toJson(voivodeships)))
                .andExpect(model().attribute("voivodeships", voivodeships))
                .andExpect(model().attribute("voivodeship_selected", voivodeship))
                .andExpect(model().attribute("cities", cities))
                .andExpect(model().hasNoErrors())
                .andExpect(view().name("/taxoffice"))
                .andExpect(status().isOk());
    }

Controller.java

    @RequestMapping(value="/select_voivodeship", method = RequestMethod.POST)
    public String selectVoivodeship (int voivodeship, Model model) {

        List<Voivodeship> voivodeships = voivodeshipService.findAll();
        model.addAttribute("voivodeships", voivodeships);
        model.addAttribute("voivodeship_selected", voivodeship);

        List<City> cities = cityService.getAllCitiesByVoivodeship(voivodeship);
        model.addAttribute("cities", cities);
        return "taxoffice";
    }
Kayris
  • 31
  • 9

1 Answers1

0

I think that the issue is that in your controller you still have int type for voivodeship, which cannot be null. Change it to Integer to match what you have in your test.

public String selectVoivodeship (Integer voivodeship, Model model) {

Objects can be null, primitive types cannot.

zawarudo
  • 1,907
  • 2
  • 10
  • 20
  • Now i have "cannot invoke "java.lang.Integer.intValue()" because "voivodeship" is null" . It shouldn't be null. because it is an id of last selected voivodeship(option from dropdown list). I think the problem is here .requestAttr("voivodeship", 10). How can i pass this parameter using mockMvc? – Kayris Apr 22 '22 at 19:35
  • https://stackoverflow.com/questions/35221911/getting-httpservletrequest-attribute-with-mockmvc Something like this, but I think that you should open a different question with that new exception and abandon this one since it has nothing to do with the title. People tend to downvote or close your questions if they are not written by the book. – zawarudo Apr 22 '22 at 19:43