Verify proper organization of JUnit test class for Calculator
Preconditions (2)
✅ Expected Result: Test class compiles and runs successfully, testAdd passes verifying add method returns correct sum
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 calculator; @BeforeEach void setUp() { calculator = new Calculator(); } @Test void testAdd() { int result = calculator.add(2, 3); assertEquals(5, result, "2 + 3 should equal 5"); } } // Calculator class for reference class Calculator { public int add(int a, int b) { return a + b; } }
This test class is named CalculatorTest following the convention of suffixing test classes with Test.
The @BeforeEach method setUp() creates a new Calculator instance before each test, ensuring tests do not share state.
The test method testAdd() is annotated with @Test and clearly describes what it tests.
Inside testAdd(), we call add(2, 3) and assert the result equals 5 using assertEquals. The assertion message helps understand failure if it occurs.
This organization keeps tests clean, readable, and independent, which is best practice in JUnit testing.
Now add two more test methods to testAdd with different inputs: (0, 0) and (-1, 1)
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class MathUtilsTest {
@Test
void testAdd() {
assertEquals(5, 2 + 3);
}
@Test
void testSubtract() {
assertEquals(1, 3 - 2);
}
@Test
void testMultiply() {
assertEquals(6, 2 * 3);
}
}import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class StringUtils {
static boolean isEmpty(String str) {
return str.length() == 0;
}
}
public class StringUtilsTest {
@Test
void testIsEmpty() {
assertTrue(StringUtils.isEmpty(""));
}
void testIsNotEmpty() {
assertFalse(StringUtils.isEmpty("abc"));
}
}Pass the test and this pattern moves unknown