SonarQube problem "Add at least one statement to this test case" for unit test with statements?

I am having problems releasing SonarQube with several of my unit tests, causing the following problem:

Add at least one statement to this test case.

Each test case resembles this format (where a number of statements are delegated to a method with general statements to avoid duplication):

@Test public void companyNameOneTooLong() throws Exception { AddressFormBean formBean = getValidBean(); formBean.setCompanyNameOne("123456789012345678901234567890123456"); assertViolation(validator.validate(formBean), "companyNameOne", "length must be between 0 and 35"); } private void assertViolation(Set<ConstraintViolation<AddressFormBean>> violations, String fieldname, String message) { assertThat(violations, hasSize(1)); assertEquals(fieldname, violations.iterator().next().getPropertyPath().iterator().next().getName()); assertEquals(message, violations.iterator().next().getMessage()); } 

Now, obviously, I could just pull the three statements from the private method and put them in the test method - but I do the same checks (in different fields) several times.

So, I thought I would try to imitate the behavior of the assertion methods by (re) throwing an AssertionError :

 private void assertViolation(Set<ConstraintViolation<AddressFormBean>> violations, String fieldname, String message) throws AssertionError { try { assertThat(violations, hasSize(1)); assertEquals(fieldname, violations.iterator().next().getPropertyPath().iterator().next().getName()); assertEquals(message, violations.iterator().next().getMessage()); } catch (AssertionError e) { throw e; } } 

Unfortunately, this approach does not work either.

What is especially important in JUnit approval methods / what is a SonarQube specifically designed to verify that an approval has been made for each test?

Alternatively - are there other approaches to achieving the same end result (avoiding duplicating a common confirmation code again and again)?

+5
source share
1 answer

Rule S2699 (tests must include statements) from the Java SonarQube analyzer does not perform cross-procedure analysis and only examines the body of methods identified as a test method (usually annotated using @Test ).

Therefore, if the only statements that will be called when the test method is executed are executed using a special method (to avoid duplication), this rule will cause a problem. This is a well-known limitation of the rule, and we will consider it only when we can effectively perform cross-procedural analysis.

Regarding the problems raised by SonarQube in such cases, you can safely mark them as Won't Fix .

In relation to detected claims, the rule considers the usual assert / fail / verify / expect methods from the following (unit test) frameworks as claims:

  • Junit
  • Fest (1.x and 2.x)
  • Assertj
  • Hamcrest
  • Mockito
  • Spring
  • Easymock
+4
source

All Articles