Test Overview
This test checks that a simple calculator addition method works correctly. It runs quickly to show how fast tests allow developers to run tests often and get quick feedback.
This test checks that a simple calculator addition method works correctly. It runs quickly to show how fast tests allow developers to run tests often and get quick feedback.
import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class CalculatorTest { @Test public void testAddition() { Calculator calc = new Calculator(); int result = calc.add(2, 3); assertEquals(5, result, "2 + 3 should equal 5"); } } class Calculator { public int add(int a, int b) { return a + b; } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | JUnit test runner initialized | — | PASS |
| 2 | Calculator object created | Calculator instance ready | — | PASS |
| 3 | Addition method called with inputs 2 and 3 | Method returns result 5 | — | PASS |
| 4 | Assert that result equals 5 | Test verifies output | assertEquals(5, result, "2 + 3 should equal 5") | PASS |
| 5 | Test finishes successfully | Test runner reports pass | — | PASS |
Why is it important to have fast tests when using JUnit?
Which JUnit annotation is used to mark a method as a test that should run quickly?
@Test to mark methods as tests.@FastTest or @SlowTest are not part of standard JUnit.Consider this JUnit test method:
@Test
void testSum() {
int result = 0;
for (int i = 1; i <= 3; i++) {
result += i;
}
assertEquals(6, result);
}What will be the test result when run?
Look at this JUnit test snippet:
@Test
void testDivide() {
int result = 10 / 0;
assertEquals(0, result);
}What is the problem and how to fix it for fast, frequent runs?
You have a large test suite that takes 30 minutes to run. How can you apply the principle of fast tests to enable frequent runs in JUnit?
Pass the test and this pattern moves unknown