【问题标题】:Test cases failing for jersey client泽西客户端的测试用例失败
【发布时间】:2019-03-30 02:45:23
【问题描述】:

我有球衣客户喜欢

 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;

【问题讨论】:

  • 没有足够的上下文来提供帮助。请使用附加代码更新问题(并格式化代码)。
  • 获取休息客户端代码:
  • @divyanayan 你真的应该把edit 这个附加信息放入问题中。不在 cmets 部分。
  • @divyanayan 展示了如何初始化被测对象以及如何注入模拟的依赖项。

标签: java unit-testing mockito


【解决方案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() 来匹配参数

以上假设模拟的网络资源被正确注入到被测主题类中。

【讨论】:

  • 尝试了 eq() 提到的方法,但又得到了空指针。是的,我已经模拟了所有必要的组件。
  • @divyanayan 那么您需要在问题中表明这一点,以便我们可以更好地帮助您。如果没有足够的上下文,我们只能猜测。
  • @divyanayan 格式在问题中完成。将其编辑为原始问题
  • 更新请查收
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-19
  • 2014-05-22
  • 2015-01-12
  • 2019-07-21
相关资源
最近更新 更多