【发布时间】:2015-10-03 11:40:27
【问题描述】:
我正在尝试使用“任何”匹配器来存根此 getKeyFromStream 方法。我尝试过更加明确和不明确(anyObject()),但似乎无论我尝试什么,这个存根都不会在我的单元测试中返回 fooKey。
我想知道是因为它受到保护还是我遗漏了其他东西或做错了什么。我在整个测试中还有其他 when/then 语句正在运行,但由于某种原因,这里不是。
注意:getKeyFromStream 一般使用 byteArrayInputStream,但我正在尝试将其与 InputStream 匹配,我都尝试过均无济于事。
public class FooKeyRetriever() //Mocked this guy
{
public FooKey getKey(String keyName) throws KeyException {
return getKeyFromStream(getKeyStream(keyName, false), keyName);
}
//Stubbed this method to return a key object which has been mocked
protected FooKey getKeyFromStream(InputStream keyStream, String keyName){
//Some code
return fooKey;
}
}
单元测试
@Mock
private FooKeyRetriever mockKeyRetriever;
@Mock
private FooKey fooKey;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
@Test
public void testGetFooKey() throws Exception {
when(foo.getKeyFromStream(any(InputStream.class),any(String.class))).thenReturn(fooKey);
FooKey fooKey = mockKeyRetriever.getKey("irrelevant_key");
assertNotNull(fooKey);
}
【问题讨论】:
-
不要相信
protected方法可以被 Mockito 存根。如果你存根getKey会发生什么? -
你是如何初始化 mockFooKey 的?
-
@AndyTurner 抱歉,我刚刚添加了那个。模拟注释。
-
您尝试对来自某个对象
foo的调用进行存根调用,但测试其他对象mockFooKey的结果;显然这行不通 -
乍得 - 这就是你初始化 foo 的方式。 mockFooKey 呢?
标签: java unit-testing mockito stubbing