Ensure Test Cases Contain Tests
What is it?
This practice is essential for ensuring that JUnit or similarly named test files (like *Test
, *Tests
, *TestCase
) or classes inheriting from TestCase
indeed contain concrete test methods.
Why apply it?
Having test files or classes without appropriate test methods can lead to false assumptions regarding coverage, making you believe that the associated functionality is thoroughly tested when it's not.
How to fix it?
Verify that each test class named according to a supported test framework convention, or implementing TestCase
, holds actual test methods.
Examples
Example 1:
Negative
This negative example shows a test class without any actual test methods, which could be misleading about test coverage.
public class CalculatorTest { /* Noncompliant */
}
Example 2:
Positive
This positive example includes a test class with a concrete test case, ensuring clarity and accurate test coverage reporting.
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class CalculatorTest { /* Compliant */
@Test
public void testAddition() {
Calculator calculator = new Calculator();
int result = calculator.add(2, 3);
assertEquals(5, result);
}
}
Negative
This negative example demonstrates a misnamed class that might be assumed to contain tests, which it doesn't.
public class StringUtilsTests { /* Noncompliant */
// No test methods present
}
Example 3:
Positive
A properly structured test file with test methods ensuring the functionality under test is covered.
import org.junit.jupiter.api.Test;
public class StringUtilsTests { /* Compliant */
@Test
public void testIsEmptyShouldReturnTrueForEmptyString() {
StringUtils utils = new StringUtils();
assertTrue(utils.isEmpty(""));
}
@Test
public void testIsEmptyShouldReturnFalseForNonEmptyString() {
StringUtils utils = new StringUtils();
assertFalse(utils.isEmpty("Hello"));
}
}