Xcode 7.3中的UITesting中的launchArguments无法正常工作

dre*_*kka 4 xcode ui-testing ios

我一直在Xcode 7.3中编写UI测试,最近想添加一个启动参数来在应用程序中启用一些测试代码.我最初尝试设置,XCUIApplication().launchArguments因为有几个人在各种帖子中做过,但他们不会工作.

周围挖看来,两者launchArgumentslaunchEnvironment不能成为UI测试中设置好,即使API文档说,他们可以.

此外,当我尝试在UI测试方案中设置启动参数和环境变量时,它们也没有传递到应用程序,在单元测试或运行应用程序时,它们是.

这是我为证明这一点所做的快速测试的副本,所有这些测试都失败了.

import XCTest

class LaunchDebugUITests: XCTestCase {

    func testLaunchArgumentsSetting() {
        XCUIApplication().launchArguments = ["abc"]
        print("Arguments \(XCUIApplication().launchArguments)")
        XCTAssertTrue(XCUIApplication().launchArguments.contains("abc"))
    }

    func testLaunchArgumentsAppending() {
        XCUIApplication().launchArguments.append("abc")
        print("Arguments \(XCUIApplication().launchArguments)")
        XCTAssertTrue(XCUIApplication().launchArguments.contains("abc"))
    }

    func testLaunchEnvironmentSetting() {
        XCUIApplication().launchEnvironment = ["abc":"def"]
        print("Environment \(XCUIApplication().launchEnvironment)")
        XCTAssertEqual("def", XCUIApplication().launchEnvironment["abc"])
    }

    func testLaunchEnvironmentAppending() {
        XCUIApplication().launchEnvironment["abc"] = "def"
        print("Environment \(XCUIApplication().launchEnvironment)")
        XCTAssertEqual("def", XCUIApplication().launchEnvironment["abc"])
    }

} 
Run Code Online (Sandbox Code Playgroud)

有人遇到过这种情况么?你有工作吗?

dre*_*kka 14

Apple回复我,并告诉我我使用XCUIApplication()不正确.

你不应该 XCUIApplication() 多次调用.

我读过的很多博客多次拨打这个电话,大多数情况下并不重要.事实上,许多博客文章都将该函数视为访问单例.我有一种感觉这是不正确的,因为它看起来不对,但我认为其他人会说得对.

但事实并非如此.它不访问单例,实际上每次调用时都会创建一个新的XCUIApplication实例.因此我的代码失败了,因为我在一个实例上设置启动参数,然后创建另一个实例启动.

所以我的测试应该看起来像这样:

func testLaunchArgumentsSetting() {
    let app = XCUIApplication()
    app.launchArguments = ["abc"]
    print("Arguments \(app.launchArguments)")
    XCTAssertTrue(app.launchArguments.contains("abc"))
    app.launch()
}
Run Code Online (Sandbox Code Playgroud)


Mic*_*ael 2

然后,您还需要启动您的应用程序并在应用程序中检查参数。我是这样做的...

func testFooBar() {
    // given
    app.launchArguments = ["shouldDoBar", "shouldDoFoo"]

    // when
    app.launch()

    // then
}   
Run Code Online (Sandbox Code Playgroud)

然后在你的应用程序中

int main(int argc, char *argv[]) {
    NSArray *arguments = [[NSProcessInfo processInfo] arguments];

    if ([arguments containsObject:@"shouldDoBar"]) {
       doBar();
    }

    if ([arguments containsObject:@"shouldDoFoo"]) {
       doFoo();
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

您可能希望参数在更适合您使用的地方进行检查(并且可能也包含在 a 中#ifdef DEBUG ... #endif以避免传送它)。