How would you mock dependencies that are passed to a method as parameters?

When a dependency is passed into a method as a parameter rather than injected into the class, you mock it the same way - create it with mock(), then pass the mock instance directly as the method argument.

Key Points: • Create the mock with mock(DependencyType.class) before calling the method under test. • Stub its behavior with when()/thenReturn() (or the do-family for void methods) so it responds predictably. • Pass the mock as the argument to the method being tested, exactly as you would a real instance. • After the call, use verify() to confirm the method under test interacted with the passed-in mock correctly. • This pattern is common for strategy-style or callback parameters where the dependency isn't a class field.

Example: For a method processOrder(Order order, PaymentStrategy strategy), you'd mock PaymentStrategy, stub pay() to return true, and pass it directly into processOrder() to verify the order is confirmed.

Code Example:

PaymentStrategy strategy = mock(PaymentStrategy.class);
when(strategy.pay(100.0)).thenReturn(true);

boolean confirmed = orderProcessor.processOrder(order, strategy);

assertTrue(confirmed);
verify(strategy).pay(100.0);

Interview Tip: A concise interview answer is:

"I mock the parameter type with mock(), stub its expected behavior, and pass the mock directly as the method argument, just like a real object. Afterward I can use verify() to confirm the method under test interacted with that parameter correctly."