mock method with generic and extends in return type(具有泛型的模拟方法并在返回类型中扩展)
问题描述
是否可以使用签名 Set< 模拟(使用 mockito)方法?扩展汽车>getCars() 没有抑制警告?我试过了:
Is it possible to mock (with mockito) method with signature Set<? extends Car> getCars() without supress warnings? i tried:
XXX cars = xxx;
when(owner.getCars()).thenReturn(cars);
但无论我如何声明 cars,我总是会遇到编译错误.例如,当我这样声明时
but no matter how i declare cars i alway get a compilation error.
e.g when i declare like this
Set<? extends Car> cars = xxx
我得到标准的通用/模拟编译错误
i get the standard generic/mockito compilation error
The method thenReturn(Set<capture#1-of ? extends Car>) in the type OngoingStubbing<Set<capture#1-of ? extends Car>> is not applicable for the arguments (Set<capture#2-of ? extends Car>)
推荐答案
使用 doReturn-when 备用存根语法.
Use the doReturn-when alternate stubbing syntax.
被测系统:
public class MyClass {
Set<? extends Number> getSet() {
return new HashSet<Integer>();
}
}
和测试用例:
import static org.mockito.Mockito.*;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
public class TestMyClass {
@Test
public void testGetSet() {
final MyClass mockInstance = mock(MyClass.class);
final Set<Integer> resultSet = new HashSet<Integer>();
resultSet.add(1);
resultSet.add(2);
resultSet.add(3);
doReturn(resultSet).when(mockInstance).getSet();
System.out.println(mockInstance.getSet());
}
}
不需要错误或警告抑制
这篇关于具有泛型的模拟方法并在返回类型中扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:具有泛型的模拟方法并在返回类型中扩展
基础教程推荐
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 多个组件的复杂布局 2022-01-01
