带有generics的mock方法,并以返回类型扩展
是否可以使用签名Set getCars()
来模拟(使用mockito)方法Set getCars()
Set getCars()
而没有Set getCars()
警告? 我试过了:
XXX cars = xxx; when(owner.getCars()).thenReturn(cars);
但无论我如何宣布cars
我总是得到编译错误。 例如,当我宣布这样的时候
Set cars = xxx
我得到标准的通用/ mockito编译错误
The method thenReturn(Set) in the type OngoingStubbing<Set> is not applicable for the arguments (Set)
使用doReturn-when备用存根语法。
被测系统:
public class MyClass { Set extends Number> getSet() { return new HashSet(); } }
和测试用例:
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 resultSet = new HashSet (); resultSet.add(1); resultSet.add(2); resultSet.add(3); doReturn(resultSet).when(mockInstance).getSet(); System.out.println(mockInstance.getSet()); } }
无需错误或警告抑制