1

点击按钮后,UIImagePickerController 会显示为模态视图控制器,代码如下:

UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
imagePicker.delegate = self;
[self presentViewController:imagePicker animated:YES completion:nil];

它在模拟器和设备上运行良好,但我想为它添加一个单元测试(使用 GHUnit)并试图测试presentedViewController 不是零。

但是,当我运行测试时,我会在控制台上打印出下面的警告。有谁知道如何解决这个问题,以便我可以正确测试?

Warning: Attempt to present <UIImagePickerController: 0xab5e990> on <UINavigationController: 0xab5a790> whose view is not in the window hierarchy!

顺便说一句 - 我已经设置 shouldRunOnMainThread 为这个特定的测试文件返回 YES 。

4

1 回答 1

0

在单元测试期间,您的 ViewController 不会显示在 Window 上,因此它不能显示其他协调器。您需要创建一个 UIWindow,例如在您的 setup 方法中,并在测试中的窗口上显示 UINavigationController。

final class YourTest: XCTestCase {

    private var window: UIWindow!

    override func setUp() {
        super.setUp()

        window = UIWindow()
    }

    override func tearDown() {
        window = nil
        super.tearDown()
    }

    func testSomething() {
        let controller = YourCustomController()
        window.rootViewController = controller
        window.makeKeyAndVisible()

        controller.callSomeMethod()
        ...
    }

    ...
}
于 2021-02-26T11:31:13.923 回答