Testing: The Practice Exam

Testing: The Practice Exam in Java: Writing a unit test is like taking a Practice Exam before the real test (Production). 1.

Concept Explanation

Writing a unit test is like taking a Practice Exam before the real test (Production).

  1. The Question (The Test Case): "If I give you 2 and 2, do you give me 4?"
  2. The Answer (assertEquals): You check if the actual answer matches the expected one.
  3. The Cheat Sheet (Mockito): Sometimes your code depends on a Database or a Web Service that isn't available during the "exam." Mockito allows you to create a Fake version of those dependencies that just says "Yes" to everything you ask.

Core Syntax (JUnit 5)

@Test
void whenAddingTwoNumbers_thenSumIsCorrect() {
    Calculator calc = new Calculator();
    int result = calc.add(10, 5);
    
    // Assertions
    assertEquals(15, result, "The sum should be 15");
    assertTrue(result > 0);
}

Mocking with Mockito

@Mock
UserRepository repo;

@InjectMocks
UserService service;

@Test
void testGetUser() {
    // Tell the "Fake" repo what to do
    when(repo.findById(1)).thenReturn(new User("Harsh"));
    
    User u = service.getUser(1);
    assertEquals("Harsh", u.getName());
}

Best Practices

  • The AAA Pattern:
  • Arrange: Set up the objects.
  • Act: Run the method you want to test.
  • Assert: Check if the result is correct.
  • Test One Thing: Don't put 50 assertions in one test. If the test fails, you want to know exactly why.

Practice Exercises

  1. The Exception Test: Write a test that check if a method throws an IllegalArgumentException when you give it invalid input (Hint: Use assertThrows).
  2. The Mockito Verify: Research verify(mock, times(1)). How do you check if your service actually called the "Save" method on the database?
  3. The TDD: Research "Test Driven Development." Why do some developers write the "Practice Exam" before they write the actual code?