模仿方法与泛型和扩展返回类型 [英] mock method with generic and extends in return type
本文介绍了模仿方法与泛型和扩展返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以使用签名 Set <?>来模拟(使用mockito)方法?延伸车> getCars()
没有禁止警告?我试过:
XXX cars = xxx;
when(owner.getCars())。thenReturn(cars);
但无论我如何声明汽车
i总是得到一个编译错误。
例如,当我声明像这样
Set <?延伸车> cars = xxx
我得到标准的通用/ mockito编译错误
然后返回类型为OngoingStubbing< Set<捕获#1-of?的方法然后返回(Set< capture#1 of?extends Car>延伸Car>>不适用于参数(Set< capture#2-of?extends Car>)
解决
<$> p $ p>
被测系统:
<$> p $ p>
public class MyClass {
Set< ;?扩展Number> getSet(){
返回新的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());
$ b $ p $不需要错误或警告抑制
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);
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>)
解决方案 Use the doReturn-when alternate stubbing syntax.
System under test:
public class MyClass {
Set<? extends Number> getSet() {
return new HashSet<Integer>();
}
}
and the test case:
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());
}
}
No errors or warning suppression needed
这篇关于模仿方法与泛型和扩展返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文