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


基础教程推荐
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01