Which of the following best explains why using test design patterns improves test quality in JUnit?
Think about how patterns help humans understand and manage code.
Test design patterns give a clear, repeatable way to write tests. This consistency helps anyone reading or updating tests to understand them quickly, reducing mistakes and improving maintenance.
Consider two JUnit tests for the same method. One uses a setup pattern, the other repeats setup code in each test. What is the output when both tests pass?
import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class CalculatorTest { private Calculator calc; @BeforeEach public void setup() { calc = new Calculator(); } @Test public void testAdd() { assertEquals(5, calc.add(2, 3)); } @Test public void testSubtract() { assertEquals(1, calc.subtract(3, 2)); } } // Versus import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class CalculatorTestNoPattern { @Test public void testAdd() { Calculator calc = new Calculator(); assertEquals(5, calc.add(2, 3)); } @Test public void testSubtract() { Calculator calc = new Calculator(); assertEquals(1, calc.subtract(3, 2)); } }
Think about what @BeforeEach does in JUnit.
Both tests run and pass correctly. The first uses @BeforeEach to set up the Calculator once per test, reducing repeated code. The second repeats setup in each test method. Both work, but the pattern improves clarity and reduces duplication.
Which JUnit assertion best improves test quality by clearly showing the expected and actual values when a test fails?
Consider which assertion provides the clearest failure message.
assertEquals(expected, actual) clearly shows both expected and actual values in failure messages, making debugging easier. Other assertions may only show true/false without details.
A JUnit test suite sometimes fails randomly. The tests share a static list that is modified in some tests. What pattern change can fix this flaky behavior?
Think about test isolation and shared mutable state.
Using @BeforeEach to create a fresh list before each test ensures tests do not affect each other, preventing flaky failures caused by shared mutable state.
Which JUnit 5 pattern correctly implements a parameterized test that runs the same test logic with multiple input values?
@ParameterizedTest
@ValueSource(ints = {1, 2, 3})
void testIsPositive(int number) {
assertTrue(number > 0);
}Look for the correct annotation and method signature for parameterized tests.
Option C uses @ParameterizedTest with @ValueSource and a parameter in the method signature, which is the correct pattern in JUnit 5 for running the same test with multiple inputs.