How do you structure a test case in JUnit?

A well-structured JUnit test case follows the Arrange-Act-Assert pattern: set up the test's preconditions, invoke the behavior under test, then verify the outcome.

Key Points: • Arrange: create the objects, mocks, and input data the test needs, often in a @BeforeEach method if shared across tests. • Act: call the single method or operation actually being tested, ideally in one clear statement. • Assert: use assertion methods like assertEquals, assertTrue, or assertThrows to confirm the expected outcome. • Keeping the three sections visually separated (even with blank lines) makes tests easier to read and review. • Each test should assert on one logical behavior; multiple unrelated assertions in one test make failures harder to diagnose.

Example: A test for a discount calculator arranges a cart with two items, acts by calling calculateTotal(), and asserts the result equals the expected discounted price.

Code Example:

@Test
void appliesTenPercentDiscount() {
    // Arrange
    Cart cart = new Cart();
    cart.addItem(new Item("Book", 100.0));

    // Act
    double total = cart.calculateTotal(0.10);

    // Assert
    assertEquals(90.0, total);
}

Interview Tip: A concise interview answer is:

"I structure every test with Arrange, Act, Assert - set up the inputs and dependencies, call the one thing being tested, then verify the outcome with an assertion. Keeping those three phases distinct makes tests easy to read and quick to debug when they fail."