In JUnit testing, some developers argue that each test method should contain only one assertion. What is the main reason for this preference?
Think about how test failures are reported and how debugging is simplified.
Having a single assertion per test helps quickly pinpoint which specific check failed, making debugging easier and faster.
Consider the following JUnit test method:
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
public class SampleTest {
@Test
void testMultipleAssertions() {
assertEquals(5, 2 + 3);
assertEquals(4, 2 * 2);
assertEquals(6, 2 + 2);
}
}What will be the outcome when this test runs?
import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; public class SampleTest { @Test void testMultipleAssertions() { assertEquals(5, 2 + 3); assertEquals(4, 2 * 2); assertEquals(6, 2 + 2); } }
JUnit stops executing a test method when an assertion fails.
The first two assertions pass, but the third assertion fails because 2 + 2 equals 4, not 6. The test fails at the third assertion.
Given this JUnit test method:
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
public class CalculatorTest {
@Test
void testAddAndSubtract() {
assertEquals(7, Calculator.add(3, 4));
assertEquals(1, Calculator.subtract(5, 4));
assertEquals(10, Calculator.add(5, 5));
}
}If the second assertion fails, what is the main issue with having all assertions in one test method?
Think about how JUnit handles assertion failures inside a test method.
When an assertion fails, JUnit stops executing the current test method, so any assertions after the failure are not run. This can hide other potential failures.
JUnit 5 introduced a feature that allows multiple assertions to be checked in a single test method, reporting all failures at once instead of stopping at the first failure. What is this feature called?
It groups assertions and reports all failures together.
The assertAll method allows grouping multiple assertions so that all are executed and all failures are reported together.
Analyze the following JUnit 5 test method:
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
public class MathTest {
@Test
void testMultipleFailures() {
assertAll("Multiple checks",
() -> assertEquals(10, 5 + 5),
() -> assertEquals(3, 1 + 1),
() -> assertTrue(2 > 3)
);
}
}What will be the result when this test runs?
assertAll runs all assertions and reports all failures together.
The first assertion passes (5 + 5 = 10). The second assertion fails (1 + 1 = 2, expected 3). The third assertion fails (2 > 3 is false). Both failures are reported together.