You want to isolate a class under test by replacing its dependency with a test double that records interactions but does not implement any real logic. Which test double should you use?
Think about which test double lets you verify method calls after the test runs.
A Spy records interactions with the dependency and allows verification of method calls without implementing full logic. Mocks also verify calls but are usually pre-programmed with expectations. Stubs provide canned responses, and Fakes have working implementations.
What is the output of the following JUnit test when run?
import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; public class PaymentProcessorTest { interface PaymentGateway { boolean charge(double amount); } static class PaymentGatewayStub implements PaymentGateway { public boolean charge(double amount) { return true; // always succeeds } } static class PaymentProcessor { private PaymentGateway gateway; public PaymentProcessor(PaymentGateway gateway) { this.gateway = gateway; } public boolean process(double amount) { return gateway.charge(amount); } } @Test void testProcessPayment() { PaymentGateway stub = new PaymentGatewayStub(); PaymentProcessor processor = new PaymentProcessor(stub); boolean result = processor.process(100.0); assertTrue(result); } }
The stub always returns true for charge, so process should succeed.
The stub implementation of PaymentGateway always returns true for charge, so the process method returns true, making the assertion pass.
Given a mock object mockService in JUnit with Mockito, which assertion correctly verifies that process() was called exactly once?
mockService.process();
Mockito uses verify() with times() to check call counts.
Option A uses Mockito's verify method with times(1) to check that process() was called once. Other options are invalid syntax or incorrect usage.
A test using a fake database implementation fails because data is not saved as expected. Which is the most likely cause?
Fakes have working implementations; if data is not saved, the implementation may be wrong.
Fakes simulate real behavior. If data is not saved, the fake's save method likely has a bug or incomplete implementation.
You have a service that depends on a slow external API. You want to test your service's logic without calling the real API, but also want to verify that your service calls the API with correct parameters. Which test double combination is best?
Consider separating behavior simulation and interaction verification.
A stub provides canned responses to simulate the API, while a spy wraps the stub to record and verify calls. This combination isolates logic and verifies interactions effectively.