【问题标题】:How can you change orientation for testing on XCTest for iOS?如何更改 XCTest for iOS 上的测试方向?
【发布时间】:2016-06-08 15:12:16
【问题描述】:

我正在尝试使用 XCTestCase 在不同方向测试我的 iOS 应用程序。我需要一种以编程方式改变方向的方法。我尝试在 2 种方法中执行此操作,但都没有改变方向(方向保持为 UIInterfaceOrientationPortrait)。

尝试 1

[UIApplication sharedApplication].statusBarOrientation = UIInterfaceOrientationLandscapeLeft;`

尝试 2

[[UIDevice currentDevice] setValue:[NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft] forKey:@"orientation"];`

当我阅读 [[UIApplication sharedApplication] statusBarOrientation] 是否有其他方法可以更改方向以进行测试?

【问题讨论】:

    标签: ios objective-c xctest xctestcase


    【解决方案1】:

    Swift 代码:

    XCUIDevice.shared.orientation = UIDeviceOrientation.portrait;
    

    【讨论】:

    • orientationUIDevice 上是只读的,但在XCUIDevice 上不是。这非常有效。
    • 因“等待方向更改确认超时”而崩溃。
    • 这不再适用于 Xcode 13,除非您的测试目标是 XCUITest 目标。
    【解决方案2】:

    使用以下解决方案。在设置方法中进行。

    [[UIDevice currentDevice] setValue:
                          [NSNumber numberWithInteger: UIInterfaceOrientationPortrait]
                                forKey:@"orientation"];
    

    它对我有用。

    【讨论】:

    • 这在测试功能中对我有用 - 我不需要将它添加到 setUp()
    • 错误:无法分配给属性:'orientation' 是一个 get-only 属性
    • 这适用于我在常规 XCTests 中的 iOS 15 SDK / Xcode 13 上。谢谢!
    【解决方案3】:

    这应该可以,我正在随机更改方向,因为我正在运行几个测试,我希望这很有用

            // Set a random device orientation
        let orient = [UIDeviceOrientation.portrait , UIDeviceOrientation.portraitUpsideDown, UIDeviceOrientation.landscapeLeft, UIDeviceOrientation.landscapeRight]
        XCUIDevice.shared().orientation = orient[Int(arc4random_uniform(UInt32(orient.count)))]
    

    【讨论】:

    • 错误:无法调用非函数类型'XCUIDevice'的值
    【解决方案4】:

    如果您想在XCTest 环境中运行设备旋转测试,我目前最知名的策略是:

    • 在模拟器中,确保设置了自动旋转设备选项。
    • 创建一个 XCTest Host 应用程序并确保其 info.plist Supported interface orientations 部分已完全删除(您不能在生产应用程序中这样做,因为 appStore 会拒绝它。)
    • 在宿主应用程序委托中实现-application:supportedInterfaceOrientationsForWindow: 并返回UIInterfaceOrientationMaskAll。这将有效地替换以前的 info.plist 条目。
    • 然后在您的测试中,在需要时拨打私人[UIDevice.currentDevice setValue:@(UIDeviceOrientation…) forKey:@"orientation"];
    • 这会产生动画效果,因此请等到所有窗口都通过检查它们的框架改变了它们的方向,然后继续您的测试。
    • 为了加快测试中的动画速度,set window.layer.speed = 100。这使动画速度提高了 100 倍,希望您的测试也能如此。

    【讨论】:

    • 这个答案对我帮助很大,谢谢!不知道为什么它被否决了。这是正确回答问题的唯一答案,这是针对单元测试,而不是 UI 测试。还有一个提示...如果您想在 CI 上进行这项工作并且需要始终设置“自动旋转设备”,您可以使用defaults write com.apple.iphonesimulator RotateWindowWhenSignaledByGuest true
    猜你喜欢
    • 2013-10-08
    • 1970-01-01
    • 2014-02-13
    • 2016-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-22
    • 1970-01-01
    相关资源
    最近更新 更多