I would like to test my controller with
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class MyTest {
@LocalServerPort
int port;
@Autowired
TestRestTemplate rest;
String myUrl = ...;
@Test
public void testSequence() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
String requesString = ...
HttpEntity<String> request = new HttpEntity<>( requesString, headers );
String response = rest.postForObject(myUrl, request, String.class);
here I need to hardcode myUlr
with something like
String.format("http://localhost:%d/my/endpint/path", port);
where my/endpint/path
depends on annotations I applied to my controller class and it's methods.
But can I derive it programmatically having class name and method name?
CodePudding user response:
Of course you could extract the @RequestMapping
path from your REST controller using reflection and combine it with the path from a handler method in it, but it's really not worth the hassle and it is much easier to put them into public constants and use those to construct the resulting url in your test. Also, constructing an url before testing it is actually a part of the test - you check that your api url looks like you expect it to.
CodePudding user response:
If I understand your question properly the one way which I am aware of is below:
public static String[] extractWebServiceDetails(HandlerMethod handlerMethod) {
String methodURI[] = handlerMethod.getMethod().getAnnotation(RequestMapping.class).value();
return methodURI;
}
Here you can use this at class level for extracting Controller
level URI by calling :
public static String[] extractWebServiceDetails(HandlerMethod handlerMethod) {
String classURI[] = handlerMethod.getClass().getAnnotation(RequestMapping.class).value();
return classURI;
}
Only constraint with this is you need to have instance of HandlerMethod for deriving these values.