I have a simple controller REST:
@RestController
@RequestMapping("/employees")
public class EmployeeController {
@Autowired
private EmployeeRepository repository;
@GetMapping("")
List<Employee> all() {
return repository.findAll();
}
@GetMapping("/{id}")
Employee one(@PathVariable Long id) {
return repository
.findById(id)
.orElseThrow(() -> new EmployeeNotFoundException(id));
}
}
Further I write a test for this controller.
public class EmployeeControllerTest {
@Autowired
private WebApplicationContext context;
private MockMvc mockMvc;
@Before
public void setup() {
mockMvc = MockMvcBuilders
.webAppContextSetup(context)
.build();
}
@Test
public void all() throws Exception {
this.mockMvc.perform(get("/employees"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$", hasSize(2)))
.andExpect(jsonPath("$[0].id", is(1)))
.andExpect(jsonPath("$[0].name", is("John")))
.andExpect(jsonPath("$[0].role", is("admin")))
.andExpect(jsonPath("$[1].id", is(2)))
.andExpect(jsonPath("$[1].name", is("Mike")))
.andExpect(jsonPath("$[1].role", is("user")));
}
@Test
public void one() throws Exception {
int id = 1;
this.mockMvc.perform(get("/employees/{id}", id))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(jsonPath("id", is(1)))
.andExpect(jsonPath("name", is("John")))
.andExpect(jsonPath("role", is("admin")));
}
}
But the problem is that there is too much duplication of the name of the route "/employees". And if there are requirements to change the name of the route, I will have to change a hundred tests. Very bad.
Also how to eliminate duplication when using the base route and the parameter, here while only one parameter: {id}. But there may also be requirements to change the name of the parameter.
Please tell how you organize the code and eliminate duplication.
I think the best solution is to introduce a
public static final String PATH = "/employees";
variable in EmployeeController
so you can reference the "/employees" path anywhere