Reputation: 6606
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.
This is a legacy code base we can't really change so we are stuck using PowerMock to meet the test coverage requirements...
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.
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.
Upvotes: 0
Views: 3587
Reputation: 47895
The following use of whenNew
with ObjectMapper
works successfully:
@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.
Upvotes: 2