在java中模拟https请求 [英] mock https request in java

查看:859
本文介绍了在java中模拟https请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我正在编写一个应用程序,我需要能够执行以下操作:

Let's say I'm writing an application and I need to be able to do something like this:

String url = "https://someurl/";
GetMethod method = new GetMethod(URLEncoder.encode(url));
String content = method.getResponseBodyAsString();

有没有办法提供一个让我处理https请求的模拟服务器?我正在寻找的是一种编写单元测试的方法,但我需要能够模拟实际出去的部分 https:// someurl 所以我可以得到一个已知的回复。

Is there a way to provide a mock server that would let me handle the https request? What I'm looking for is a way to write unit tests, but I need to be able to mock the part that actually goes out to https://someurl so I can get a known response back.

推荐答案

你基本上有两个选择:

1。摘要对框架的调用并对此进行测试。

例如。重构代码以允许您在某些时候注入模拟实现。有很多方法可以做到这一点。例如创建一个getUrlAsString()并模拟它。 (也在上面提出)。或者创建一个返回GetMethod对象的url getter工厂。然后工厂可以被嘲笑。

E.g. refactor the code to allow you to inject a mock implementation at some point. There are many ways to do this. e.g. create a getUrlAsString() and mock that. (also suggested above). Or create a url getter factory that returns a GetMethod object. The factory then can be mocked.

2。作为测试的一部分启动应用服务器,然后针对它运行您的方法。 (这将更多是集成测试)

这可以通过多种方式实现。这可以在测试之外,例如maven jetty插件。或者测试可以以编程方式启动服务器。请参阅: http://docs.codehaus.org/display/JETTY/Embedding+Jetty

This can be achieved in an number of ways. This can be external to the test e.g. the maven jetty plugin. or the test can programmatically start up the server. see: http://docs.codehaus.org/display/JETTY/Embedding+Jetty

通过https运行会使这变得复杂,但仍然可以使用自签名证书。但我会问自己 - 你究竟要测试什么?我怀疑你确实需要测试https功能,它是一种经过验证的技术。

Running it over https will complicate this but it will still be possible with self signed certs. But I'd ask yourself - what exactly you want to test? I doubt you actually need to test https functionality, its a proven technology.

我个人会选择选项1 - 你试图测试外部库的功能。这通常是不必要的。将依赖项抽象到外部库也是一种很好的做法。

Personally I'd go for option 1 - you are attempting to test functionality of an external library. That is usually unnecessary. Also it's good practice to abstract out your dependencies to external libraries.

希望这会有所帮助。

这篇关于在java中模拟https请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆