【问题标题】:How to test if my application method handles HTTP status 404 of a REST API without actually calling that REST API如何测试我的应用程序方法是否处理 REST API 的 HTTP 状态 404 而无需实际调用该 REST API
【发布时间】:2020-08-25 16:01:36
【问题描述】:

我目前正在尝试使用 JUnit 自动化我的应用程序的一些测试。我的应用程序有一个调用第 3 方 REST API 的方法。我需要检查该方法是否正在处理像 404 这样的 HTTP 状态代码,而无需实际调用 4rd 方 API。

例如,我的方法:

public int getNumUsers(){
    //call the 3rd party API - https://example.com/api/users/count
    //return user count
}

我需要测试 getNumUsers 方法是否正在处理 HTTP 状态代码 404,这可能由 3rd 方 API - https://example.com/api/users/count 返回。

有什么建议吗?

【问题讨论】:

    标签: unit-testing testing junit automated-tests integration-testing


    【解决方案1】:

    将对“第 3 方 API”的 http 调用提取到它自己的对象中。将该对象传递给您要测试的类的构造函数。

    现在您可以在单元测试中将其替换为测试替身(存根/模拟)并控制它返回的内容。正确的结果值或错误。

    类似这样的:

    这是第三部分 API

    interface UserApi {
        int getUserCount ();
    }
    

    您的用户服务将调用此 api

    class UserService {
        private final UserApi api;
    
        UserService(UserApi api) {
            this.api = api;
        }
    
        int getUserCount() {
            // todo handle errors
            return api.getUserCount ();
        }
    }
    

    还有一些测试

    public class UserServiceTest {
    
        @Test
        public void shouldProvideUserCount() {
    
            UserService service = new UserService (new UserApi () {
                @Override
                public int getUserCount () {
                    return 1;
                }
            });
    
            // when
            int count = service.getUserCount ();
    
            // then
            assertEquals(1, count);
        }
    
        @Test(expected = UserOperationFailedException.class)
        public void shouldHandleApiError() {
            UserService service = new UserService (new UserApi () {
                @Override
                public int getUserCount () {
                    throw new ApiException();
                }
            });
    
            // when
            service.getUserCount ();
        }
    
    }
    

    您可以使用像 Mockito 这样的库来创建存根,而不是自己实现它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-15
      • 2020-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-21
      相关资源
      最近更新 更多