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());
}
}
不需要错误或警告抑制
这篇关于具有泛型的模拟方法并在返回类型中扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:具有泛型的模拟方法并在返回类型中扩展


基础教程推荐
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 降序排序:Java Map 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01