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.
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());
}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?