How do you write a test for a method with database calls in JUnit without hitting the actual database?

Testing a method with database calls without hitting a real database means mocking the data-access layer so the test exercises business logic against controlled, in-memory responses instead of a live connection.

Key Points: • Mock the repository or DAO interface with Mockito rather than connecting to an actual database. • Stub the mock's query methods with when()/thenReturn() to return fixed test data for each scenario. • This keeps the test fast, deterministic, and independent of database availability or state. • For tests that do need real persistence behavior, an in-memory database like H2, or Testcontainers with a real database, is used instead - but that's integration testing, not unit testing. • Verifying interactions with verify() confirms the code called the repository correctly, e.g. that save() was invoked exactly once.

Example: For a UserService.getUser(id) method backed by a UserRepository, mocking findById() to return a fixed User lets the test check the service's logic without any real database connection.

Code Example:

@Test
void returnsUserFromRepository() {
    UserRepository repo = mock(UserRepository.class);
    when(repo.findById(1L)).thenReturn(Optional.of(new User("Alice")));

    UserService service = new UserService(repo);
    assertEquals("Alice", service.getUser(1L).getName());
}

Interview Tip: A concise interview answer is:

"I mock the repository or DAO layer with Mockito, stubbing its query methods to return fixed test data, so the test exercises the service's logic without touching a real database. That keeps the test fast and deterministic - I'd reach for an in-memory database or Testcontainers only for genuine integration tests."