XCUITests - 通过命令行传入环境变量

XCUITests - Passing in environment variables via command line

我正在尝试通过命令行向我的 XCUI测试传递一个值。我知道可以通过以下方式为 XCTest(非 UI)执行此操作:

xcodebuild -verbose test -workspace MyWorkspace.xcworkspace -derivedDataPath derivedData -scheme "MyScheme" -configuration Debug SYMROOT="$(pwd)"/build -destination platform="iOS Simulator",name="iPad Air",OS=10.2 -only-testing:UITests/UITests -resultBundlePath logfiles MY_SETTING="setting_value" MY_OTHER_SETTING="setting_value_2"

然而,这在我的 XCUI 测试中似乎不起作用,因为代码没有进入 #ifdef MY_SETTING 块。还有另一种方法可以通过命令行将值传递给我的 XCUITest 吗?

没有通过 xcodebuild 将值传递给 UI 测试的本机方法。在 运行ning UI 测试之前,您可以使用 perl 单行代码替换项目中的值:

perl -pi -e 's/valueToReplace/replacementValue/g' <path to file to modify>

我过去曾使用此方法替换项目中的基础 URL,以便 运行 UI 针对模拟服务器进行测试。

这是可以做到的,是的,不过你少了两个步骤。

  1. 设置您的 Scheme,使环境变量的值设置为 MY_SETTING
  2. if let mySetting = ProcessInfo.processInfo.environment['MY_SETTING'] { // do whatever you want because it is defined }

有点像 Accessing user defined variables passed in from xcodebuild command line

感谢您在下面的回答,我发现这个答案最终对我有用。 Applitools 的大神帮我解决了这个问题,详细步骤如下:

The most important step is to make Xcode know about the variables we are going to pass from command line.

Lets call our variable TEST_VAR. To do this follow these steps please:

1) Open to Xcode, select TEST TARGET(not target of application) https://www.evernote.com/l/AR0BF8Te8_hFGYON8jKqIkv3grnwFky16tc

2) Select “Build Settings” and add in the “Preprocessor Macros” section TEST_VAR=$(TEST_VAR)

https://www.evernote.com/l/AR1b4QRysBlDRro3sbKH1hSy6s_2s_Qkxnw

3) Add new user-define setting by tapping “+” button and selecting “Add User-Defined Setting” https://www.evernote.com/l/AR0qflFqN2lIEoKVVzUUYRArM49Qb1d2TUE

4) Set a default value for your new custom setting https://www.evernote.com/l/AR32JBfPDhFIN76ZlJjq1eV7v8bry9WImfE

Now variable TEST_VAR is ready to use.

This is an example how I pass it to the test. My test project is inside a workspace. So I open Terminal and go to the destination folder of my workspace.

xcodebuild -workspace workspace_name\ workspace.xcworkspace/ -scheme YourSchemeName -sdk iphonesimulator -destination 'platform=iOS Simulator,name=iPhone 6,OS=10.2' -only-testing:TestTargetName/TestCaseName/testName TEST_VAR=1988 test

Inside the test I can get the value of TEST_VAR variable somehow like this: NSLog(@"TEST_VAR %li", (long)TEST_VAR);

但是,我还需要定义另一个预处理器宏来解包我传入的值的字符串值,如下所述:Accessing the value of a Preprocessor Macro definition.

所以为了检索字符串值,我做了类似的事情:

NSLog(@"TEST_VAR %s", MACRO_VALUE(TEST_VAR))

如果您需要将环境变量从您的架构传递到 XCUITes,请修改 XCTestCase -> app.launchEnvironment 对象,在此的每个测试 class方式:

Swift 3

override func setUp(){
    app.launchEnvironment = ProcessInfo.processInfo.environment
}