Java · OOP, JVM and backend craft
How do you test Java and Spring applications?
Short answer
JUnit 5 provides the test engine and Jupiter API for writing and running tests. Good suites mix fast unit tests with focused integration tests and use Mockito or Testcontainers where needed.
JUnit 5 consists of the platform, Jupiter and Vintage engines. Jupiter provides @Test, lifecycle annotations, assertions and parameterized tests. Unit tests should be fast and isolated; integration tests verify wiring, SQL or HTTP behaviour.
class OrderServiceTest {
private final OrderRepository repository = mock(OrderRepository.class);
private final OrderService service = new OrderService(repository);
@Test
void returnsEmptyWhenOrderIsMissing() {
when(repository.findById(42L)).thenReturn(Optional.empty());
assertTrue(service.find(42L).isEmpty());
}
}Choosing the test level
- Unit tests for pure logic, fast and numerous
- @WebMvcTest for controllers with mocked services
- @DataJpaTest for repositories and mapping
- @SpringBootTest for full wiring, used sparingly
- Testcontainers for real databases and message brokers
Over-mocking produces tests that pass while the real integration fails. Assert behaviour and outcomes rather than implementation details. Use parameterized tests for input matrices and name tests by the scenario and expected result.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1When would you use @WebMvcTest instead of @SpringBootTest?
- 2What is the risk of excessive mocking?
- 3How do you test database queries realistically?
- 4What is a parameterized test useful for?
Say it in the interview
I write most tests as fast unit tests with JUnit 5 and Mockito, then add focused slice tests for controllers and repositories. For real SQL behaviour I use Testcontainers rather than an in-memory database that differs from production. I avoid over-mocking because it can hide integration failures, and I assert outcomes rather than internal calls. A service that needs a full context for simple logic usually has too many responsibilities.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Java mock interview and get scored feedback on depth, clarity and confidence.