PowerMockito被模拟的final类gson.fromJson()返回空值

dnph8jn4  于 2022-11-08  发布在  其他
关注(0)|答案(1)|浏览(161)

我在主类中有这个代码-

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();
}

额外播放器.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为空?请提供帮助/建议。

xj3cbfub

xj3cbfub1#

如果您要使用标准的@Mock@InjectMocks注解以及mockito,那么是的,框架将负责将mock注入到测试中的类中(不管setter等是否存在)。
另一件事是playerMock,我假设它是测试中的类。
不要模拟测试中的类,创建一个普通的示例,然后注入依赖项... performWaiting方法似乎不接受响应String,所以你必须以某种方式注入它(除非你遗漏了一些部分):

@Test
public void test() {
    // Arrange
    String jsonResponse = "{\"status\":\"waiting\",\"no\":\"12\"}";     
    Gson gsonMock = PowerMockito.mock(Gson.class);
    ExtraPlayer extraPlayer = new ExtraPlayer();
    extraPlayer.setNo("12");
    extraPlayer.setStatus("Waiting");

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

    Player player = new Player();
    player.setGson(gsonMock);
    player.setResponse(jsonResponse);

    // Act
    player.performWaiting();

    // Assert ...
}

相关问题