About comment in method body

Now, I want to write a rule to check method body’s comments, as follows,

  public void test_xxx() {
    // given
    int number1 = 1;
    int number2 = 2;
    // when
    int result = Calcutor.add(number1, number2);
    // then
    Assertion.assertEquals(3, result);

The rule will check whether the test contains comment “given-when-then”, but the sonar doesn’t support get comment in method body, only method-level comment?

Hello @husky

If I understand correctly your question: no, there is no method available to get all comments present in the body of a method.

You can get them “by hand” though. There are probably different ways to do it, depending on your requirements. If you expect the comments to not be nested into statements, you can probably go for something like:

method.block().body().stream().flatMap(s -> s.firstToken().trivias().stream())

Note that this code will probably not work as it is (missing null check, …), but I hope it already gives you clues to continue your implementation.


Thank you! Your idea does works. :100:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.