简体   繁体   English

如何从Java集成测试修改网络连接?

[英]How to modify network connection from Java integration test?

I've written a Java class ( MyRestClient ) that needs to hit a third-party RESTful API and do some processing with the HTTP response returned from their server. 我编写了一个Java类( MyRestClient ),它需要访问第三方RESTful API并使用从其服务器返回的HTTP响应进行一些处理。 I'm now trying to write a series of successful integration tests (using JUnit as the underlying testng lib) between MyRestClient and the 3rd party API to make sure this class behaves correctly under a variety of circumstances: 我现在正在尝试在MyRestClient和第三方API之间编写一系列成功的集成测试(使用JUnit作为底层testng lib),以确保此类在各种情况下正常运行:

  • Everything is perfect (RESTful API call was correct and the server returns a meaningful response) 一切都很完美(RESTful API调用是正确的,服务器返回一个有意义的响应)
  • Bad API call and server returns an application-layer error code 错误的API调用和服务器返回应用程序层错误代码
  • A variety of non-200 HTTP codes get returned, including 403, 404 and 500 返回各种非200 HTTP代码,包括403,404和500
  • No network connection 无网络连接
  • ...etc. ...等等。

The 4th item on that list (" No network connection ") is what I'm currently stuck on. 该列表中的第4项(“ 无网络连接 ”)是我目前所坚持的。 I'm using Jersey under the hood to perform my actual REST calls, however Jersey is itself just based on java.net.* . 我正在使用Jersey来执行我的实际REST调用,但是Jersey本身只是基于java.net.* If at all possible, I'd like to "break" Jersey's/Java's ability to fire a network connection while my shouldThrowExceptionOnBadNetworkConnection() test method is executing, and then turn it back "on" so that the next test method can behave normally. 如果可能的话,我想在我的shouldThrowExceptionOnBadNetworkConnection()测试方法执行时“打破”Jersey的/ Java启动网络连接的能力,然后将其“打开”,以便下一个测试方法可以正常运行。

I've been looking at the Charles Proxy which seems to do just this, however there doesn't seem to be a Java library for managing it at runtime. 我一直在寻找看起来像这样做的Charles Proxy ,但似乎没有用于在运行时管理它的Java库。

So I ask: How do I turn Java networking "off" for a specific integration test? 所以我问: 如何针对特定的集成测试“关闭”Java网络? Thanks in advance. 提前致谢。

Make MyRestClient testable by having it declare a protected method that returns the URL and have it use that instead if a private field. 通过声明一个返回URL的受保护方法使MyRestClient可测试,并让它在私有字段中使用它。

In your JUnit test, you an anonymous class to override that method do it returns junk: 在你的JUnit测试中,你是一个匿名类来覆盖该方法它是否返回垃圾:

MyRestClient willFail = new MyRestClient() {
    protected String getUrl() {
        return "http://not.a.real.address";
    }
}

There are also mocking libraries that can do similar things 还有一些模拟库可以做类似的事情

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM