Describe different types of test doubles (mocks, stubs, spies, fakes) and explain when you would choose one over another in the context of unit testing with JUnit 5.
Java interview question for Advanced practice.
Answer
Test doubles are objects that stand in for real dependencies in a test. This isolates the unit under test. Here are the common types: Stubs: Stubs provide canned answers to method calls made during the test. They are used when you don't care about the interaction, only that your code gets a specific piece of data from the dependency to continue its execution. Use a stub when you need to control the state returned by a dependency. Example: A stub for a repository method that returns a predefined User object when called. Mocks: Mocks are objects that register which method calls they receive. In the test, you assert which methods you expected to be called on the mock. They are focused on behavior verification. Use a mock when you need to verify that your code interacts with its dependency in a specific way. Example: A mock for an email service to verify that its sendEmail method was called exactly once with the correct arguments. Spies: Spies are based on a real object and record the interactions with it, while still allowing the real methods to be called. You can also selectively stub some of its methods. Use a spy when you need to test a real object but want to verify some of its method calls or change its behavior slightly. Example: Spying on an ArrayList to verify that the add method was called, while still using the list's real implementation. Fakes: Fakes are objects that have working implementations, but are much simpler than the production version. An in-memory database is a classic example of a fake. Use a fake when you need a dependency that has complex behavior, but the real one is too slow or unavailable in a test environment. Example: A fake repository that uses an in-memory HashMap instead of connecting to a real database.
Explanation
While JUnit itself doesn't provide a mocking framework, it integrates seamlessly with popular ones like Mockito and EasyMock through its extension model.