我有球衣客户
public ClientResponse getCall(String apiName){
restClient = getRestClient();
WebResource webResource = restClient
.resource(Constants.FUELWISE_END_POINT+apiName);
return webResource.accept(Constants.APPLICATION_JSON)
.header(Constants.AUTHORIZATION_HEADER, Constants.AUTHORIZATION_VALUE).get(ClientResponse.class);
}
并具有模拟测试用例行,如:
@Test
public void getCallTest() {
when(restClient.resource(any(String.class))).thenReturn(webResource);
when(webResource.accept(any(String.class)).header(any(String.class), any(Object.class))
.get(eq(ClientResponse.class))).thenReturn(clientResponse);
restUtilityTest.getCall("messages");
}
扩展了测试Java类,以从方法getRestClient()返回restClient模拟,而不是Client.create()
使用注释通过@Mock进行模拟
堆栈跟踪错误:
This message may appear after an NullPointerException if the last matcher is returning an object
like any() but the stubbed method signature expect a primitive argument, in this case,
use primitive alternatives.
在测试用例文件中完成模拟:
@InjectMocks
private RestUtilityTest restUtilityTest;
@Mock
private Client restClient;
@Mock
private WebResource webResource;
@Mock(name = "response")
private ClientResponse clientResponse;
答案 0 :(得分:0)
确保被测对象及其依存关系正确排列。
@Test
public void getCallTest() {
//Arrange
ClientResponse clientResponse = mock(ClientResponse.class);
WebResource webResource = mock(WebResource.class);
when(webResource
.accept(any(String.class))
.header(any(String.class), any(String.class))
.get(eq(ClientResponse.class))
)
.thenReturn(clientResponse);
Client restClient = mock(Client.class);
when(restClient.resource(any(String.class))).thenReturn(webResource);
RestUtilityTest restUtilityTest = new RestUtilityTest(restClient);
//Act
ClientResponse response = restUtilityTest.getCall("messages");
//Assert
//...
}
请注意使用any(String.class)
和eq()
来匹配参数
以上假设模拟的网络资源已正确注入到受测主题类中。