是否可以在Xcode 7自动UI测试中存根HTTP请求? [英] Is it possible to stub HTTP requests in Xcode 7 automated UI tests?
问题描述
我一直在尝试使用像 OHHTTPStubs这样的工具拦截和存储/模拟Xcode 7自动UI测试中的HTTP请求,没有运气。
I've been trying to intercept and stub/mock HTTP requests in Xcode 7 automated UI tests, using tools like OHHTTPStubs, with no luck.
以下是我尝试在UI测试文件的setUp方法中使用OHHTTPStubs捕获任何HTTP请求的示例: / p>
Here's an example of how I am trying to capture any HTTP request using OHHTTPStubs in the setUp method of a UI test file:
override func setUp() {
super.setUp()
let matcher: OHHTTPStubsTestBlock = { (request) -> Bool in
return true
}
OHHTTPStubs.stubRequestsPassingTest(matcher) { (response) -> OHHTTPStubsResponse! in
return OHHTTPStubsResponse.init()
}
}
有没有关于UI测试的工作方式可以防止这种情况?有没有人能够实现这个目标?
Is there something about the way that UI testing works that prevents this? has anyone been able to achieve this?
推荐答案
正如Martijn正确指出的那样,由于UI测试的工作原理,你不能直接互动在运行时使用应用程序,因此在 XCUITestCase
中对 NSUserDefaults
等任何HTTP模拟或操作都不会影响您的应用程序。
As Martijn correctly pointed out, because of how UI tests work, you cannot directly interact with the app at runtime, so any HTTP mocking or manipulation of things like NSUserDefaults
in a XCUITestCase
will not affect your app.
如果你真的需要能够模拟HTTP或设置&拆除您的应用程序环境以进行特定的UI测试,您需要在 setUp()
方法中启动应用程序之前设置启动参数或启动环境变量 XCUITestCase
然后修改您的应用程序代码以读取启动参数或环境变量并引导测试环境。
If you really need to be able to mock HTTP or setup & teardown your apps environment for specific UI tests, you will need to set launch arguments or launch environment variables before launching the app in the setUp()
method of a XCUITestCase
and then modify your app code to read the launch arguments or environment variables and bootstrap the test environment.
示例TestCase
class MyTestCase: XCTestCase {
/**
Called before each test in this test case.
*/
override func setUp() {
super.setUp()
let app = XCUIApplication()
app.launchArguments = [ "STUB_HTTP_ENDPOINTS" ]
app.launch()
}
}
示例AppDelegate
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
#if DEBUG
if (NSProcessInfo.processInfo().arguments.contains("STUB_HTTP_ENDPOINTS")) {
// setup HTTP stubs for tests
}
#endif
return true
}
注意:为了在此示例中使用类似 OHHTTPStubs
的HTTP模拟框架,您需要使用的存根代码和任何JSON装置都将需要在您的应用目标中,而不是测试目标。
Note: In order to use an HTTP mocking framework like OHHTTPStubs
in this example, the stubbing code and any JSON fixtures you need to use will all need to be in your app target, not the test target.
这是一个非常有用的线程来阅读该主题: https://github.com/AliSoftware/OHHTTPStubs/issues/124
This is a very useful thread to read on the topic: https://github.com/AliSoftware/OHHTTPStubs/issues/124
这篇关于是否可以在Xcode 7自动UI测试中存根HTTP请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!