Xcode 7.3 中的 UITesting 中的 launchArguments 不工作

launchArguments in UITesting in Xcode 7.3 not working

我一直在 UI 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"])
    }

} 

有没有人遇到过这个?你有解决办法吗?

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

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

    // when
    app.launch()

    // then
}   

然后在您的应用中

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

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

    if ([arguments containsObject:@"shouldDoFoo"]) {
       doFoo();
    }
    ...
}

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

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

你不应该调用 XCUIApplication() 多次

我读过的许多博客都多次调用了这个函数,而且在大多数情况下这无关紧要。事实上,许多博客文章都将函数视为访问单例。我觉得这是不正确的,因为它看起来不对,但我认为其他人会做对的。

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

所以我的测试实际上应该是这样的:

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