简体   繁体   中英

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM