[英]PowerMock whenNew Not Returning Mocked Instance
I'm trying to use PowerMock to snub out a call to Jackson ObjectMapper but for some reason it isn't working and I suspect it is related to whenNew not actually providing the mocked instance when it gets instantiated in the method being tested. 我正在尝试使用PowerMock缓冲对Jackson ObjectMapper的调用,但由于某种原因它无法正常工作,我怀疑它与whenNew在所测试的方法中实例化时未实际提供模拟实例有关。
This is a legacy code base we can't really change so we are stuck using PowerMock to meet the test coverage requirements... 这是我们无法真正更改的遗留代码库,因此我们无法使用PowerMock来满足测试覆盖率要求...
I have a method that has something like the following: 我有一种方法,类似于以下内容:
private void intakeDataFromUrl(URL url) {
ObjectMapper mapper = new ObjectMapper();
DataDTO[] dataDtos = mapper.readValue(url, DataDTO[].class)
// other code
}
In the unit test I am attempting to do the following: 在单元测试中,我尝试执行以下操作:
@Test
public void test_intakeDataFromUrl() {
DataDTO[] data = this.createMockData();
ObjectMapper mapper = mock(ObjectMapper.clas);
whenNew(ObjectMapper.clas)
.withNoArguments()
.thenReturn(mapper);
// mock call to return mocked data
doReturn(data)
.when(mapper, "readValue", any(URL.class), any(DataDTO[].class))
}
But in the code being tested dataDtos is always null and then the next section of code always fails. 但是在被测试的代码中,dataDtos始终为null,然后代码的下一部分始终失败。
Edit: 编辑:
Looks like this line is maybe the problem although looking at other examples it should work. 看起来这条线可能是问题所在,尽管查看其他示例也可以。
// mock call to return mocked data
doReturn(data)
.when(mapper, "readValue", any(URL.class), any(DataDTO[].class))
I've also tried isA and eq on the last argument with no luck, still returns null. 我也尝试过最后一个参数上的isA和eq,但是没有运气,仍然返回null。
The following use of whenNew
with ObjectMapper
works successfully: 在
ObjectMapper
使用whenNew
的以下用法可以成功工作:
@RunWith(PowerMockRunner.class)
@PrepareForTest({ObjectMapper.class})
public class WtfTest {
@Test
public void test_intakeDataFromUrl() throws Exception {
String in = "in";
String out = "out";
ObjectMapper mapper = mock(ObjectMapper.class);
PowerMockito.whenNew(ObjectMapper.class)
.withNoArguments()
.thenReturn(mapper);
Mockito.when(mapper.readValue(in, String.class)).thenReturn(out);
assertEquals(out, intakeDataFromUrl(in));
}
private String intakeDataFromUrl(String url) throws IOException {
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(url, String.class);
}
}
Although this example does not use DataDTO
, it is otherwise consistent with your example and it is functional. 尽管此示例未使用
DataDTO
,但与您的示例一致,并且可以正常使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.