相关疑难解决方法(0)

如何对使用Java UUID的代码进行单元测试?

我有一段代码,希望用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)

java uuid unit-testing

6
推荐指数
2
解决办法
1万
查看次数

Mockito当/然后没有返回预期值

我正在尝试使用'any'匹配器来存根这个getKeyFromStream方法.我已经尝试过更明确且更不明确(anyObject()),但似乎无论我尝试什么,这个存根都不会在我的单元测试中返回fooKey.

我想知道是不是因为它受到了保护,或者还有其他我遗漏或做错的事情.我有其他什么时候/然后在整个测试中的语句正在工作,但由于某种原因在这里,它不是.

注意:getKeyFromStream通常使用byteArrayInputStream,但我试图将它与Inp​​utStream匹配,我试过两个都无济于事.

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)

java unit-testing mockito stubbing

0
推荐指数
1
解决办法
2万
查看次数

标签 统计

java ×2

unit-testing ×2

mockito ×1

stubbing ×1

uuid ×1