Verify Calculator operations using @Nested inner classes in JUnit
Preconditions (2)
✅ Expected Result: Both testAddPositiveNumbers and testSubtractPositiveNumbers pass successfully, showing that @Nested classes organize related tests
import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; class Calculator { int add(int a, int b) { return a + b; } int subtract(int a, int b) { return a - b; } } public class CalculatorTest { Calculator calculator = new Calculator(); @Nested class AddTests { @Test void testAddPositiveNumbers() { assertEquals(5, calculator.add(2, 3)); } } @Nested class SubtractTests { @Test void testSubtractPositiveNumbers() { assertEquals(2, calculator.subtract(5, 3)); } } }
This test class uses @Nested inner classes to group tests logically by operation type: addition and subtraction.
The Calculator class provides simple methods to add and subtract numbers.
Inside CalculatorTest, two nested classes AddTests and SubtractTests each contain one test method.
Each test method uses assertEquals to verify the expected result.
This structure helps organize tests clearly and makes it easier to maintain and understand related test cases.
Add a new @Nested class MultiplyTests with a test method that verifies multiplication of two numbers
@Nested inner classes in JUnit tests?class CalculatorTest {
@BeforeEach void setup() { System.out.println("Setup main"); }
@Test void testAdd() { System.out.println("Test add"); }
@Nested
class MultiplyTests {
@BeforeEach void setup() { System.out.println("Setup nested"); }
@Test void testMultiply() { System.out.println("Test multiply"); }
}
}What will be the output when running the testMultiply method?class OuterTest {
@Nested
class InnerTest {
@Test void testSomething() {}
}
@Test void testOuter() {}
}Which of the following is a problem that will cause the tests NOT to run as expected?@Nested classes to separate addition and subtraction tests. Which of the following code snippets correctly applies @Nested classes with proper setup methods so that the main setup runs before each nested test setup?Pass the test and this pattern moves unknown