0

For our REST API we have standardized on using hyphen case, i.e. GET /store-users?first-name=dan and not GET /storeUsers?firstName=dan

How can we enforce this naming convention as developers keep adding non compliant URLs to the application. Some static analysis of the spring rest controller annotations that would fail the maven build would be ideal.

2
  • 1
    Maybe you can create a custom rule in Checkstyle (or any other static code analysis tools) to validate that all @RequestMapping annotations follow the hyphen case naming convention. You can then integrate these tools with your Maven build, so the build fails if any non-compliant URLs are found.
    – Hagelslag
    Commented Jul 10 at 5:11
  • You can use this post from the SonarQube community to get started: community.sonarsource.com/t/…. It is also doing the same thing as you, checking the values of a RequestMapping annotation. Then, you just need to implement your logic to check for your coding style of choice
    – BIBOO unit
    Commented Jul 10 at 5:21

2 Answers 2

0

A Simple Unit Test should do:

@Autowired
private ApplicationContext applicationContext;

@Test
public void allEndpointsShouldBeKebabCase() {
    RequestMappingHandlerMapping requestMappingHandlerMapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
    var methodMap = requestMappingHandlerMapping.getHandlerMethods();
    //Insert your endpoint path checks here
}
3
  • How does this answer OP‘s question?
    – Jens
    Commented Jul 10 at 4:38
  • I don't think this is what OP was looking for. As far as I can tell, they wanted to preemptively reject bad endpoints, not test for them after the fact.
    – Andrew Yim
    Commented Jul 10 at 4:52
  • 1
    @Jens By default maven surefire will fail the build if there are failed Unit tests. I believe this is what OP is looking for.
    – vuongdt23
    Commented Jul 10 at 6:39
0

you have at least 3 options:

  • in tests let spring create your context, get all the generated urls, assert them, fail the test if assertion fails (something like user @vuongdt23 suggested)

  • use ArchUnit and scan your classes, annotations, assert them, fail the test

  • create custom plugin / checks for static analysis tool (sonar? checkstyle?) and plug it into your CI/CD pipeline

imho, doing it in tests instead of external static analyis tool would be the easiest way

Not the answer you're looking for? Browse other questions tagged or ask your own question.