如何模拟objectmetadata对象



我有以下方法:

private boolean success(String key) {
    if (cachedStatus.containsKey(key)) {
      return cachedJobsStatus.get(key).booleanValue();
    }
    String status = String.format("%s/%s", key, SUCCESS);
    ObjectMetadata meta = getMetadata(key);
    Boolean isOK = Boolean.FALSE;
    if (meta != null) {
      isOK = Boolean.TRUE;
   }
    cachedStatus.put(objectKey, isOK);
    return isOK.booleanValue();
}

我创建了此测试:

public void successTest() throws Exception {
    String key = "data1-1-33-a.txt/part-00002-attempt_201711232056_0000_m_000002_2";
    //test when _SUCCESS exists
    boolean result = Whitebox.invokeMethod(APIClient, "success", key);
    Assert.assertEquals("successuccessful() failed even when _SUCCESS exists",
        true, result);

我相信测试失败了,因为元不存在,因此ISOK无法设置为真。

要使测试正常工作,我认为我必须为Meta创建一个模拟,但我不确定如何。有人可以建议吗?

这是getMetadata()方法:

protected ObjectMetadata getMetadata(String key) {
    try {
      ObjectMetadata m = client.getMetadata(bucket, key);
      return m;
    } catch (AmazonClientException e) {
      LOG.warn(e.getMessage());
      return null;
    }
}

可能最简单的方法是模拟您的client

@RunWith(MockitoJUnitRunner.class)
public class MyTest {
   @Mock
   private AmazonS3Client client;   // or whatever
   @Mock
   private ObjectMetadata mockedObjectMetadata;
   @InjectMocks
   private MyClassToTest toTest; // Put your class that has "client" here
   @Test
   public void someTest() {
       Mockit.when(client.getMetadata(Mockito.anyString(), Mockito.anyString()).thenReturn( mockedObjectMetadata ); // voila
       boolean result = toTest("someRandomKey");
       ///etc.
   }
}

相关内容

  • 没有找到相关文章

最新更新