user8933752
user8933752

Reputation: 109

MockMVC @PathVariable not work when using String

Mockmvc test not work when Pathvariable is a String but work on int. Here is my code:

@Controller
@RequestMapping("/etablissement/{typeEtablissement}")
public class EtablissementController{
    @RequestMapping(method = RequestMethod.GET)
    public String accueil(@PathVariable("typeEtablissement") String typeEtablissement) {
        return "/test";
    }
}

// somewhere in my test
mockMvc.perform(get("/etablissement/{typeEtablissement}", "test")).andExpect(status().isOk()); // Error 400

But, if I use int instead of String it works

@RequestMapping(method = RequestMethod.GET)
public String accueil(@PathVariable("typeEtablissement") int typeEtablissement) {
    return "/test";
}

// somewhere in my test
mockMvc.perform(get("/etablissement/{typeEtablissement}", 123)).andExpect(status().isOk()); // Works

Using Object also work

public String accueil(@PathVariable("typeEtablissement") Object typeEtablissement) {}

Thanks for your help !

Upvotes: 0

Views: 514

Answers (2)

Greg
Greg

Reputation: 126

Strange cause it means typeEtablissement is an int. You can also create a new variable after with valueOf:

@GetMapping("/{typeEtablissement}/{something2}/{something3}")
    public List<Object> extract(
            @PathVariable String typeEtablissement,
            @PathVariable String something2,
            @PathVariable String something3) {

String typeEtablissementConverted = String.valueOf(typeEtablissement );

List<Object> object = objectService.extractDatas(typeEtablissementConverted, something2, something3);

return object;
}

Upvotes: 0

Greg
Greg

Reputation: 126

Here is an example of a GetMapping who should help you :

@GetMapping("/{typeEtablissement}/{something2}/{something3}")
    public List<Object> extract(
            @PathVariable String typeEtablissement,
            @PathVariable String something2,
            @PathVariable String something3) {

List<Object> object = objectService.extractDatas(typeEtablissement, something2, something3);

return object;
}

Upvotes: 1

Related Questions