PowerMockito Mocked final class gson.fromJson()返回null

时间:2017-07-05 13:14:55

标签: unit-testing junit mockito powermockito

我在主类中有这段代码 -

try {
    extraPlayer = gson.fromJson(jsonResponse, ExtraPlayer.class);// this returns null
} catch (Exception e) {
    e.printStacktrace();
}

此处 extraPlayer将显示为空 我嘲笑了@Mock Gson gsonMock;

此处 ExtraPlayer 是一个静态类。

我已经写了这个测试代码 -

@Test
public void test() {
    String jsonResponse = "{\"status\":\"waiting\",\"no\":\"12\"}";
    when(playerHandlerMock.resetPlayer("someString", "someString", "1",true    
         )).thenReturn(jsonResponse);       
    Gson gsonMock = PowerMockito.mock(Gson.class);
    ExtraPlayer extraPlayer = new ExtraPlayer();
    extraPlayer.setNo("12");
    extraPlayer.setStatus("Waiting");

    PowerMockito.mockStatic(ResetModemResponse.class); // using this for static class but didn't work.

    PowerMockito.when(gsonMock.fromJson(jsonResponse, ExtraPlayer.class)).thenReturn(extraPlayer);

    playerMock.performWaiting();
}

ExtraPlayer.java

public static class ExtraPlayer{

    String no;
    String status;      

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getNo() {
        return code;
    }

    public void setNo(String no) {
        this.no = no;
    }

}

我已将这些注释添加到测试类 -

@RunWith(PowerMockRunner.class)
@PrepareForTest(Gson.class)

为什么extraPlayer为空?请帮忙/建议。

1 个答案:

答案 0 :(得分:0)

如果你要使用标准fs.readFileSync('C:/tmp/hello') @Mock注释与mockito,那么是的,框架将负责将模拟注入到被测试的类中(无论是否存在安装者等。)。

另一件事是@InjectMocks,我假设它是被测试的类。

不要模拟测试中的类,创建一个普通实例,然后注入依赖项...... playerMock方法似乎不接受响应String,所以你必须以某种方式注入(除非你留下了一些部分):

performWaiting