This rule targets tests written with the JUnit Jupiter API (JUnit 5 and later), i.e. annotated with org.junit.jupiter.api.Test. While
JUnit 4 assertions defined in org.junit.Assert continue to work in such tests, using them should be avoided.
JUnit 5 ships with its own assertion library, org.junit.jupiter.api.Assertions, which is richer and consistent with the rest of the
JUnit 5 API. Using JUnit 4 assertions in a JUnit 5 test is inconsistent. Because the two APIs differ in subtle ways, it can also lead to confusion and
errors:
org.junit.Assert takes the message as the first
argument, org.junit.jupiter.api.Assertions as the last.Supplier<String>, so the failure message can be built lazily, which is not possible with JUnit
4.Replace each call to a method of org.junit.Assert with the equivalent method of org.junit.jupiter.api.Assertions. If a
failure message is provided, move it from the first to the last argument position.
import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertEquals;
class MyTest {
@Test
void shouldComputeAnswer() {
assertEquals("values should match", 42, compute()); // Noncompliant
}
}
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class MyTest {
@Test
void shouldComputeAnswer() {
assertEquals(42, compute(), "values should match");
}
}
If you find the JUnit 5 assertion library limited, consider using a dedicated assertion library such as AssertJ or Hamcrest.