FP in S2784: Add at least one assertion to this test case

Hello there,

I’m experimenting false positives regarding no assertion in test cases.

  • I’m using IntelliJ 2020.1 build IU-221.6668.121 and SonarLint 4.6.0.16682 right now but this is happening for older versions too.
  • Context: Spring Framework 5.2.5 project using spring-test and org.springframework.test.web.servlet.ResultActions.andExpect()
  • End2end tests extends a base class which got custom methods to test common scenarios: successfull requests, invalid, 404, etc.
  • A minimal example:
public abstract class ControllerTest extends ServiceTest {

    protected MvcResult performSuccessfulRequest(MockHttpServletRequestBuilder requestBuilder) throws Exception {
        return performRequest(requestBuilder, null, null, status().isOk());
    }

    protected MvcResult performRequest(MockHttpServletRequestBuilder requestBuilder, String content,
                                       RequestPostProcessor withUser, ResultMatcher statusMatcher, ResultMatcher... resultMatchers) throws Exception {
        requestBuilder.contentType(MediaType.APPLICATION_JSON);

        if (content != null) {
            requestBuilder.content(content);
        }

        if (withUser != null) {
            requestBuilder.with(withUser);
        }

        ResultActions resultActions = mockMvc.perform(requestBuilder);
        for (ResultMatcher resultMatcher : resultMatchers) {
            resultActions.andExpect(resultMatcher);
        }

        return resultActions.andExpect(statusMatcher)
                .andDo(print())
                .andReturn();
    }

}
@RunWith(SpringRunner.class)
public class HeadquarterControllerTest extends ControllerTest {

     @Test
        public void createHeadquarter_onlyName() throws Exception {
            performSuccessfulRequest(MockMvcRequestBuilders.post("/headquarters"));
        }

}

As you can see there’s andExpect inside performRequest.

Don’t know if there’s a way to avoid these false positives.

Regards.

Hi,

If the test is using a helper method to assert, not located in the same file, the analyzer will not understand it and report a FP. In SonarQube/SonarCloud, it is possible to tune the rule in the quality profile to consider method performSuccessfulRequest as an assertion.

SonarLint doesn’t support rules parameter when not using connected mode. So today options are:

  • disable the rule
  • use connected mode to benefit from rule parameter

I created a ticket, but this is low priority:
https://jira.sonarsource.com/browse/SLI-387

2 Likes

Hi @Julien_HENRY, thank you for your reply and for creating a ticket. I’ll look into connected mode althought I was trying not relying on it to avoid too many request to our sonar server.

There’s an ‘easy’ workaround that I don’t like too much which consist in adding @Test(expected = Test.None.class)

Regards.