You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 any Supplier instance, regardless of its generic type T. This bypasses the type erasure limitations that made your earlier attempts with raw Supplier or Supplier<Object> fail.
  • Flexible Answer: The lambda in doAnswer extracts the supplier from the invocation, calls its get() method, and returns the result—preserving the original behavior of your recordElapsedTime function 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> and Runnable call in your test suite, so you won't have to write separate mocks for Supplier<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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 14:07:32