我有一段代码,希望用Java UUID(UUID.randomUUID())填充响应对象的一个属性.
如何从外部对此代码进行单元测试以检查此行为?我不知道将在其中生成的UUID.
需要测试的示例代码:
// To test whether x attribute was set using an UUID
// instead of hardcode value in the response
class A {
String x;
String y;
}
// Method to test
public A doSomething() {
// Does something
A a = new A();
a.setX( UUID.randomUUID());
return a;
}
Run Code Online (Sandbox Code Playgroud) 我正在尝试使用'any'匹配器来存根这个getKeyFromStream方法.我已经尝试过更明确且更不明确(anyObject()),但似乎无论我尝试什么,这个存根都不会在我的单元测试中返回fooKey.
我想知道是不是因为它受到了保护,或者还有其他我遗漏或做错的事情.我有其他什么时候/然后在整个测试中的语句正在工作,但由于某种原因在这里,它不是.
注意: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;
}
}
Run Code Online (Sandbox Code Playgroud)
单元测试
@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);
}
Run Code Online (Sandbox Code Playgroud)