有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

jersey客户端的java测试用例失败

我有一个像这样的客户

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

并具有mockito测试用例行,如:

   @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类以返回restClient mock而不是Client。从方法getRestClient()创建()

使用@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;

共 (1) 个答案

  1. # 1 楼答案

    确保被测对象及其依赖关系安排正确

    @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()来匹配参数

    上面假设模拟的web资源被正确地注入到测试的主题类中