我在主类中有这段代码 -
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 为空?请帮忙/建议。
如果您要在mockito中使用标准的
@Mock
和@InjectMocks
注释,那么是的,框架会负责将mock注入到被测试的类中(无论setter等是否存在)。
另一件事是
playerMock
,我认为它是正在测试的类。
不要模拟被测试的类,创建一个普通实例,然后注入依赖项...
performWaiting
方法似乎不接受响应字符串,所以你也必须以某种方式注入它(除非你留下了一些部分)出):
@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 ...
}