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

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.

@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.

Last updated: 16 July 2026

Previous question: How would you test private methods in JUnit? Should you test them directly?

Next question: How does JUnit handle concurrency when running multiple test methods in parallel?

More JUnit interview questions

All JUnit questions