如何在spock框架中模拟HttpURLConnection及其responseCode
我正在使用Java并使用groovy中的spock框架编写junit,想要模拟HttpUrlConnection并设置connection.getResponseCode()>> 200 根据不同情况。
URL url = new URL(proxySettingDTO.getTestUrl());
HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy);
connection.setRequestMethod("GET");
connection.setUseCaches(false);
...
LOGGER.debug("Response code ::{} ",connection.getResponseCode()); //200 or 403
我尝试过使用
HttpURLConnection httpURLConnection = Mock()
URL url = new URL(proxySettingDTO.getTestUrl());
url.openConnection(_) >> httpURLConnection
但它不起作用。
I am using Java and writing junit using spock framework in groovy, want to mock the HttpUrlConnection and set connection.getResponseCode() >> 200 as per different cases.
URL url = new URL(proxySettingDTO.getTestUrl());
HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy);
connection.setRequestMethod("GET");
connection.setUseCaches(false);
...
LOGGER.debug("Response code ::{} ",connection.getResponseCode()); //200 or 403
I have tried using
HttpURLConnection httpURLConnection = Mock()
URL url = new URL(proxySettingDTO.getTestUrl());
url.openConnection(_) >> httpURLConnection
But it is not working.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的问题有几个问题:
In
url.openConnection(_) >>> httpURLConnection
您正在尝试存根方法结果,但您的URL
对象未声明为模拟、存根或间谍。也就是说,你的尝试注定会失败。即使您尝试模拟
URL
,该 JDK 类也是最终的,即您无法模拟它,因为模拟是子类。被测试的类通过调用
url.openConnection(proxy)
来获取HttpURLConnection
。由于 (3),该方法不可模拟,因此您应该将连接创建外部化到辅助类ConnectionManager
中,然后将模拟实例注入到被测试的类中,以使其可测试。一般来说,测试是一种设计工具,而不仅仅是用测试来覆盖代码。如果测试很困难,则意味着组件设计耦合得太紧。让测试帮助使用 TDD(测试驱动开发)或至少测试驱动重构来驱动您的设计,即使后者有点晚了并且意味着返工。如果您对组件进行更多的解耦,例如不创建您的类在内部依赖的对象实例,而是允许 API 用户注入它们(例如通过构造函数或 setter),那么可测试性会更好,并且您的头痛也会减少。
这个怎么样?
<一href="https://gwc-experiment.appspot.com/?g=groovy_2_5&codez=eJyNVE2PmzAQvfMrRjmBRNmPQ1qtxF62VXvYVatk c468MEncBcPazkdV5b93bAMmQNu9kGC_mXnvzQw1y17ZFiHHRGVyX65LpjTKRGm6qA4oN0V1TN4-3sxv5ref5kHAy7qSGlRdZa9JwcQ2Wd aY8Q3PmOaVCIKSYERBN63rh0oIzMzpE4GfUWnAk0ark7iIgd8BEIENaIKEkX0F2PIDijuYMSgpGrIuGZRMEGUZg0S9l4KLLYxBR653dFx LpMxcYE5oIi0UEirHma3RY-hy9jK0JykY9h0tgKpG4QPDdQzrCO7vHczoXi0e_b2PI0moFw2JB-IQ2rDb6-sGcA780z6YyI0BAqqXn5QN9 iInQsYl2Csj24quZXX6ZcxgBXx-_m6i_maZU22stqlsS1IQeIRV-x5aGT9Mzii2V_b_ErWmipQ_pOORS1FgM-OJ-qqJc4l6V-V9wq5Xqo H02uE4dXwSMsm7N7ArTRu7zqYezajmGbiB6wQ0fteSH5hGx955ND73qhzCv19g3zEmTr93sVc2_l-t-D0F_BzpHVeJTUG988L6F71a6aSy Bjw17WNpbirtDxca_tWgliOtAOxl0Q7X4jEcsDBtNkatZBFGURM1Wp7-CKcwtVwjtslgPYlF7Cxoq_iQRJmFfNsTjyc7sOHs65fn2TRwR SJZtkMVblihcAI0Wu9un8fjOhwJZ9xSS7PWfW86S2c7Uq_urq7sd_pD851uv2TTVcZz5bJdmjxwrOld3F8dT4Nuhhb33HU0zsEf33Me5A" rel="nofollow noreferrer">在 Groovy Web 控制台中尝试一下。
There are several things wrong in your question:
In
url.openConnection(_) >> httpURLConnection
you are trying to stub a method result, but yourURL
object is not declared as a mock, stub or spy. I.e., your attempt is doomed to fail.Even if you would try to mock a
URL
, that JDK class is final, i.e. you cannot mock it, because mocks are subclasses.The class under test fetches the
HttpURLConnection
by callingurl.openConnection(proxy)
. Because of (3), the method is not mockable, so you should externalise connection creation into a helper classConnectionManager
and then inject a mock instance into the class under test in order to make it testable.In general tests are a design tool, not just for covering your code with tests. If testing is difficult, it means that the component design is too tightly coupled. Let the tests help drive your design using TDD (test-driven development) or at least test-driven refactoring, even though the latter is a bit late and means rework. If you decouple your components more, e.g. by not creating the object instances your class depends on internally but enabling API users to inject them, e.g. via constructors or setters, testability is much better and you have fewer headaches.
How about this?
Try it in the Groovy web console.