Java
Summary - JUnit test
Combine @Test, assertEquals and @ParameterizedTest to write a calculator test.
Summary - JUnit test
In this group you saw the basics of JUnit 5: @Test for test methods, assertEquals and assertThrows for verification, @BeforeEach for setup, @ParameterizedTest for multiple inputs and @DisplayName for readable names.
Now you will combine these into a mini task: writing arithmetic tests for a Calculator class. You will use pieces from all previous lessons. This summary shows how real unit tests are written.
Exercise Write Calculator tests
Define a Calculator class with add(int a, int b) and divide(int a, int b) methods (divide should throw ArithmeticException on zero). In a CalculatorTest class, write @Test methods testAdd and testDivide that call assertEquals(7, c.add(3, 4)) and assertEquals(2, c.divide(10, 5)). Add a main method that prints add(3, 4).
Show example solution
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class Calculator {
int add(int a, int b) {
return a + b;
}
int divide(int a, int b) {
return a / b;
}
}
class CalculatorTest {
@Test
void testAdd() {
Calculator c = new Calculator();
assertEquals(7, c.add(3, 4));
}
@Test
void testDivide() {
Calculator c = new Calculator();
assertEquals(2, c.divide(10, 5));
}
public static void main(String[] args) {
Calculator c = new Calculator();
System.out.println(c.add(3, 4));
}
}
Exercise Add a parameterized add test
Define a new ParameterTest class. Write a @ParameterizedTest method testAdd with @CsvSource({"2, 3, 5", "4, 4, 8"}); it takes int a, int b, int expected and calls assertEquals(expected, a + b). Add a main method that loops over (2,3) and (4,4) pairs, adds them and prints the count of matches with the expected values.
Show example solution
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import static org.junit.jupiter.api.Assertions.*;
class ParameterTest {
@ParameterizedTest
@CsvSource({"2, 3, 5", "4, 4, 8"})
void testAdd(int a, int b, int expected) {
assertEquals(expected, a + b);
}
public static void main(String[] args) {
int matches = 0;
int[][] pairs = {{2, 3, 5}, {4, 4, 8}};
for (int[] p : pairs) {
if (p[0] + p[1] == p[2]) matches++;
}
System.out.println(matches);
}
}
Test yourself
-
How do you know a test method failed?
- When the class does not compile
- When there is no main method
- When @Test is missing
- When an assertion throws an exception
Show answer
When an assertion throws an exception — When an assertion fails, it throws and the test is marked failed.
-
Match the JUnit 5 summary
- @Test
- Makes a method a test
- assertEquals
- Compares values
- @BeforeEach
- Sets up before each test
- @ParameterizedTest
- Runs multiple inputs
Next lesson: Mock