Java 如何模拟 HTTP 响应
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43900186/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to mock a HTTP response
提问by
I'm a newbie to Java Unit test. The issue I'm facing is that I need to develop a JUnit test to send requests to a server'API to test two methods: addUser
and deleteUser
. If I want to add/delete a user from the server, I need to get an authentication token from the server; However, due to some issue on the server side, I currently can't get a valid token. So what comes to my mind, is to mock the server's behavior that if the server receives requests from the Unit test, it could response with a JSON data which indicates the status of the add/delete-user operations.
我是 Java 单元测试的新手。我面临的问题是我需要开发一个 JUnit 测试来将请求发送到服务器的 API 以测试两种方法:addUser
和deleteUser
. 如果我想从服务器添加/删除用户,我需要从服务器获取身份验证令牌;但是,由于服务器端的一些问题,我目前无法获得有效的令牌。所以我想到的是模拟服务器的行为,如果服务器收到来自单元测试的请求,它可以响应一个 JSON 数据,指示添加/删除用户操作的状态。
Because I'm totally new to JUnit. I have no clue how to implement the operation. So my question is what is probably the easiest way to apply the mock?
因为我对 JUnit 完全陌生。我不知道如何实施该操作。所以我的问题是应用模拟最简单的方法是什么?
回答by M2E67
HttpResponse httpResponse = mock(HttpResponse.class);
see this: Mocking Apache HTTPClient using Mockito
回答by Andrei Tigau
You can do it by using the HTTP Unit Testing from Google.
您可以使用Google的HTTP 单元测试来实现。
In order to generate a simple HTTP response you can use this code :
为了生成简单的 HTTP 响应,您可以使用以下代码:
HttpTransport transport = new MockHttpTransport();
HttpRequest request = transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
HttpResponse response = request.execute();
You can also customize your testing by overriding the implementation of the MockHttpTransport class.
您还可以通过覆盖 MockHttpTransport 类的实现来自定义您的测试。
You can check herethe repo of this for more details. I think it can be suitable for you.
回答by codeflush.dev
You can simulate start a test-http-server in your unit-test. There are several frameworks to do it. For example Mockserverand Wiremock.
您可以在单元测试中模拟启动 test-http-server。有几个框架可以做到这一点。例如Mockserver和Wiremock。