Mockito:仅使用局部变量的测试方法



我有MyRestService类的以下方法:

public Address getOfficeLocation(String id){
    RestClient restClient = new RestClient(tokenOauthUrl);
    String url = String.format(officeAddress, id);
    JSONObject jsonObject = restClient.get(url, null, credentials);
    return AddressParser.parseOfficeAddress(jsonObject);
}

我想调用restClient.get。我写了以下测试:

@Mock
private MyRestService myService;
@Mock
private RestClient restClient;
@Test
public void getOfficeLocationTest(){
    myService.getOfficeLocation(any(String.class));
    Mockito.verify(restClient, Mockito.times(1)).get(any(String.class), any(MultivaluedMap.class), any(Credentials.class));
}

我想这是完全错误的方法。我得到测试失败:Wanted but not invoked: Actually, there were zero interactions with this mock.

如何使方法可以测试?

您的SUT应该是这样的东西

class YourClass {
    @Inject
    private RestClient restClient;    //Injecting RestClient
    public Address getOfficeLocation(String id){
        String url = String.format(officeAddress, id);
        JSONObject jsonObject = restClient.get(url, null, credentials);
        return AddressParser.parseOfficeAddress(jsonObject);
    }
}

您的测试代码

@Mock
private MyRestService myService;

我相信Myrestservice是您正在测试的系统(SUT),因此不应嘲笑它,而必须创建它的新对象

也许像

@InjectMocks
private MyRestService myService;

这将把模拟的RestClient注入MyRestService

相关内容

  • 没有找到相关文章

最新更新