Spring MVC Integration test - how to search for query matching path?

We have a controller, let's say something like this:

@Controller @RequestMapping("/api") public Controller UserController { @RequestMapping("/users/{userId}") public User getUser(@PathVariable String userId){ //bla } } 

We have an integration test, for example:

 @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @SpringApplicationConfiguration(classes= MyApp.class) @IntegrationTest("server:port:0") public class UserControllerIT { @Autowired private WebApplicationContext context; @Test public void getUser(){ test().when() .get("/api/users/{userId}", "123") .then() .statusCode(200); } } 

How can we avoid hard coding "/ api / users / {userId}" in the test? How can we search for a query by name. The above query mapping should have a default name of UC # getUser

The only thing I've seen is something like MvcUriComponentsBuilder, which seems to require it to be used in the context of the request (so it will be used in .jsps to create URLs for controllers).

What is the best way to handle this? Should I show mappings as static strings on controllers? I would prefer to at least avoid this.

+5
source share
2 answers

I ended up working with @DavidA's suggestion and just used reflection:

 protected String mapping(Class controller, String name) { String path = ""; RequestMapping classLevel = (RequestMapping) controller.getDeclaredAnnotation(RequestMapping.class); if (classLevel != null && classLevel.value().length > 0) { path += classLevel.value()[0]; } for (Method method : controller.getMethods()) { if (method.getName().equals(name)) { RequestMapping methodLevel = method.getDeclaredAnnotation(RequestMapping.class); if (methodLevel != null) { path += methodLevel.value()[0]; return url(path); } } } return ""; } 

I don’t know how often we will use it, but this is the best I could find.

Use in a test class:

 when().get(mapping(UserAccessController.class, "getProjectProfiles"), projectId) .then().assertThat().body(....); 
+1
source

Sort of:

 URI location = MvcUriComponentsBuilder.fromMethodCall(on(UserController.class).getUser("someUserId").build().toUri(); 
+3
source

Source: https://habr.com/ru/post/1242715/


All Articles