PowerMockito Mocked final class gson.fromJson() Returns null



我在主类中有这段代码 -

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)

为什么额外播放器为空?请帮助/建议。

如果您要使用标准@Mock并使用 mockito@InjectMocks注释,那么是的,框架将负责将模拟注入到被测试的类中(无论是否存在 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 ...
}

相关内容

  • 没有找到相关文章

最新更新