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

时间:2016-12-06 14:01:35

标签: java unit-testing 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.

如何让我的方法可测试?

1 个答案:

答案 0 :(得分:1)

你的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