0

代码:

public class AccountService(){

private ObjectMapper mapper = new ObjectMapper();

public Account getAccount(){
    try {

        ClientResponse response = RestUtility.getAccounts();

        if(CLientResponse.OK.Status == response.getClientResponseStatus()){
            return mapper.readValue(response.getEntity(String.class), Account.class)
        } 

    } catch(Exception e){
        log.error(e.getMessage(), e);
    }

    return null;
    }
}

我怎样才能模拟这项服务?RestUtility 是一个静态实用程序,不能被 mockito 模拟。我想要的只是让我的方法返回一个“模拟”帐户列表。这种架构甚至可能吗?

4

2 回答 2

1

要模拟您使用的静态方法PowerMock。或者你可以在你的RestUtility类上创建包装器。应在构造函数上提供对此包装器的引用。

于 2013-11-07T07:40:27.930 回答
0

如果您更改为

public class AccountService() {
    protected ClientResponse getResponse() { return RestUtility.getAccounts(); }

    public Account getAccount() {
        try {
            ClientResponse response = getResponse();
            ...
        }
}

getResponse()使用 Mockito 或其他模拟框架进行模拟是微不足道的。或者更简单:

public class AccountServiceTest {
    class TestableAccountService extends AccountService {
        @Override
        protected ClientResponse getResponse() { return <yourmockresponsegoeshere>; }
    }

    @Test
    public void testMe() {
        AccountService ac = new TestableAccountService();
        assertThat( ac.getAccount.size() , equalTo( 1 ) );
        // etc
        ...
    }

干杯,

于 2013-11-07T07:46:44.520 回答