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

参数化测试中如何配合Mockito.when使用泛型类,无需编写独立测试方法

解决方案

编译报错的核心原因有两点:

  1. Converter接口的convert是重载方法,分别接收StuffA、StuffB类型参数,编译期需要明确参数类型才能匹配到对应方法
  2. 原有代码存在逻辑错误:classByType.get(type).cast(type)尝试对Type枚举实例做类型转换,既不符合convert方法的入参要求,运行时也会抛出类型转换异常。

最优实现方案

使用Mockito的doReturnAPI替代when().thenReturn,配合类型匹配器即可在不拆分测试方法的前提下完成mock,修改后的测试代码如下:

@ParameterizedTest
@EnumSource(value = Type.class)
void testHandle(Type type) {
    MyStuff myStuff = mock(classByType.get(type));
    Thing thing = mock(Thing.class);
    when(myStuff.getType()).thenReturn(type);
    // 核心修改:doReturn避开编译期重载校验,any动态匹配运行时的参数类型
    doReturn(thing).when(converter).convert(any(classByType.get(type)));

    handler.handle(myStuff);

    verify(sender).send(thingArgumentCaptor.capture());
    assertThat(thingArgumentCaptor.getValue()).isEqualTo(thing);
}

方案说明

  • doReturn语法的编译期类型校验宽松,不会强制要求匹配到确定的重载方法,适配运行时才确定参数类型的场景
  • any(Class)匹配器会动态匹配当前type对应的Stuff子类,不管是StuffA还是StuffB都能正确匹配到对应的convert重载方法

内容的提问来源于stack exchange,提问作者why_vincent

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 19:57:03