Mockito与Java泛型冲突:如何Mock任意泛型Supplier参数?
Solution to Mock Generic
recordElapsedTime for Any Supplier<T> Absolutely! You can create a single mock setup that works for any Supplier<T> type, eliminating the need to duplicate code for each specific generic parameter. The key is leveraging Mockito's generic argument matching and a flexible Answer that handles any supplier.
Step-by-Step Implementation
Here's how to rewrite your mock to handle all Supplier<T> instances:
// Mock the Supplier<T> version doAnswer(invocation -> { // Extract the Supplier argument (position 2) and invoke it Supplier<?> supplier = invocation.getArgument(2); return supplier.get(); }) .when(mockLogsBasedMetricService) .recordElapsedTime( any(MeasurementBundle.Builder.class), any(DistributionMetric.class), ArgumentMatchers.<Supplier<?>>any());
Why This Works
- Generic Wildcard Matching:
ArgumentMatchers.<Supplier<?>>any()explicitly tells Mockito to match anySupplierinstance, regardless of its generic typeT. This bypasses the type erasure limitations that made your earlier attempts with rawSupplierorSupplier<Object>fail. - Flexible Answer: The lambda in
doAnswerextracts the supplier from the invocation, calls itsget()method, and returns the result—preserving the original behavior of yourrecordElapsedTimefunction without tying it to a specific return type.
Bonus: Mock the Runnable Version Too
Since you mentioned a Runnable overload, you can set up a similar generic mock for it:
// Mock the Runnable version doAnswer(invocation -> { Runnable runnable = invocation.getArgument(2); runnable.run(); return null; // Required for void methods }) .when(mockLogsBasedMetricService) .recordElapsedTime( any(MeasurementBundle.Builder.class), any(DistributionMetric.class), any(Runnable.class));
Key Benefits
- No Redundant Code: This single mock setup works for every
Supplier<T>andRunnablecall in your test suite, so you won't have to write separate mocks forSupplier<Workspace>,Supplier<User>, etc. - Preserves Original Behavior: Your test code retains the actual logic of the operations you're wrapping, avoiding null returns and keeping test cleanup minimal.
内容的提问来源于stack exchange,提问作者Jay Carlton
相关产品推荐
相关产品推荐

