在iOS单元和ui测试中忽略了Scheme语言设置

And*_*der 12 xcode ios xctest xcode-ui-testing

我的最终目标是发布

xcodebuild test
Run Code Online (Sandbox Code Playgroud)

从命令行为不同的语言选择不同的方案.

目前我有两个方案,它们之间唯一的区别是应用程序语言.在一个方案中,它是英语,另一个是西班牙语.如果我使用xCode来运行应用程序它运行良好,它是使用我选择的方案中指定的语言启动的,EN或ES都可以.

如果我从xCode运行测试,则忽略语言设置.无论我选择哪种方案,都无关紧要,它始终显示为设备语言.在模拟器上相同.使用xcodebuild测试选择方案运行测试时也是如此.(向方案添加echo命令可确保选择正确的方法)

在方案编辑器中,选中"使用运行操作的参数和环境变量".

我究竟做错了什么?

谢谢.

Tom*_*ina 27

是的,似乎在XCTest测试中忽略了方案中提供的所有环境变量和启动参数.

但是,您可以在测试中以编程方式设置语言,例如在setUp()方法中:

override func setUp() {
    super.setUp()

    // Put setup code here. This method is called before the invocation of each test method in the class.

    let app = XCUIApplication()
    app.launchArguments += ["-AppleLanguages", "(en-US)"]
    app.launchArguments += ["-AppleLocale", "\"en-US\""]

    app.launch()

}
Run Code Online (Sandbox Code Playgroud)

现在,您可以扩展此方法并执行类似的Snapshot操作:

必须从快照向xcodebuild命令行工具传递2件事:

  • 设备类型通过xcodebuild参数的destination参数传递

  • 语言通过临时文件传递,该文件在运行测试之前由快照写入,并在启动应用程序时由UI测试读取

最后,为了更改架构基础上的语言,您可以执行以下操作:

1.为Test创建一个创建临时文件的预执行脚本:

mkdir -p ~/Library/Caches/xcode-helper
echo "en-US" > ~/Library/Caches/xcode-helper/language.txt
Run Code Online (Sandbox Code Playgroud)

2.加载文件setUp()并设置应用程序语言:

override func setUp() {
    super.setUp()

    let app = XCUIApplication()

    let path = NSProcessInfo().environment["SIMULATOR_HOST_HOME"]! as NSString
    let filepath = path.stringByAppendingPathComponent("Library/Caches/xcode-helper/language.txt")


    let trimCharacterSet = NSCharacterSet.whitespaceAndNewlineCharacterSet()
    let language = try! NSString(contentsOfFile: filepath, encoding: NSUTF8StringEncoding).stringByTrimmingCharactersInSet(trimCharacterSet) as String

    app.launchArguments += ["-AppleLanguages", "(\(language))"]
    app.launchArguments += ["-AppleLocale", "\"\(language)\""]

    app.launch()
}
Run Code Online (Sandbox Code Playgroud)

从现在开始,Xcode将使用方案的预执行脚本中指定的语言/语言环境运行测试.

UPDATE

事实证明,测试不会忽略该方案中提供的参数.参数实际上传递给测试本身,但不传递给测试的应用程序.这可能是意料之外的,但这是有道理的.

话虽这么说,你需要做的就是:

1. 在方案中设置-AppleLanguages (en-US)-AppleLocale en_US启动测试的参数

屏幕截图 - 设置<code>XCUIApplication</code>在调用<code>launch()</code>方法之前,将测试中的启动参数传递给实例</h3>

<pre><code>override func setUp() {
    super.setUp()

    // Put setup code here. This method is called before the invocation of each test method in the class.

    let app = XCUIApplication()
    app.launchArguments += NSProcessInfo().arguments
    app.launch()
}
</code></pre><a target=Run Code Online (Sandbox Code Playgroud)

  • 好的,这是关于UI测试.单元测试怎么样? (5认同)
  • 这不适用于单元测试。有人有解决方法吗? (2认同)