单元测试:警告在视图不在窗口层次结构中的视图上显示视图

DrP*_*nce 3 unit-testing ios swift

我有一个带有 UICollectionView 的 UIViewController,它不是我的应用程序的根,而是通过 segue 到达的。这个 UICollectionView 有 UICollectionViewCells 有一个带有 UITapGestureRecognizer 的 imageView,当触发时它有助于呈现一个 UIAlertViewController。当我收到此警告时,我在测试我的 show alert 方法时遇到了麻烦:

“尝试在视图不在窗口层次结构中的 * 上呈现!”

我的代码片段写在下面

class ViewControllerTests : XCTestCase {

var vc : ViewController!

override func setUp() {
    super.setUp()

    let storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
    vc = storyboard.instantiateViewControllerWithIdentifier("LocationsVC") as! ViewController

    vc.loadView()

}

override func tearDown() {
    super.tearDown()
}

func testshowLocationActionSheet(){
    vc.viewDidLoad()
    vc.viewDidAppear(true)
    vc.collectionView.reloadData()

    let indexPath = NSIndexPath(forRow: 0, inSection: 0)

    var cell = vc.collectionView(vc.collectionView, cellForItemAtIndexPath: indexPath) as! FranchiseLocatorViewCell
    XCTAssertNotNil(cell)

    cell = vc.collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! ViewCell
    XCTAssertNotNil(cell)

    let tapGesture = UITapGestureRecognizer()
    let mapview = UIImageView()
    mapview.tag = 1
    mapview.addGestureRecognizer(tapGesture)
    cell.mapImageView = mapview
    vc.showActionSheet(tapGesture)

    XCTAssertTrue(vc.presentedViewController is UIAlertController?)
}
}
Run Code Online (Sandbox Code Playgroud)

视图控制器中的真实功能片段如下

func showActionSheet(sender: UITapGestureRecognizer){
    let location = self.locationArray[(sender.view?.tag)!] as Location

    self.actionSheet = UIAlertController(title: "Open direction in Apple maps", message: "", preferredStyle: UIAlertControllerStyle.ActionSheet)

    let cancelAction = Action.makeActionWithTitle("Cancel", style: UIAlertActionStyle.Cancel) { (UIAlertAction) -> Void in
        self.actionString = "Cancel"
        self.actionSheet?.dismissViewControllerAnimated(true, completion: nil)
    }

    let okayAction = Action.makeActionWithTitle("Yes", style: UIAlertActionStyle.Destructive) { (UIAlertAction) -> Void in
        self.actionString = "Yes"
    }

    self.actionSheet?.addAction(cancelAction)
    self.actionSheet?.addAction(okayAction)

    self.presentViewController(self.actionSheet!, animated: true, completion: nil)

}
Run Code Online (Sandbox Code Playgroud)

dan*_*dan 5

您的视图控制器不在窗口中,因此它无法呈现另一个视图控制器。您应该能够在您的setUp方法中创建一个窗口。

override func setUp() {
    super.setUp()

    let storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
    vc = storyboard.instantiateViewControllerWithIdentifier("LocationsVC") as! ViewController

    let window = UIWindow(frame: UIScreen.mainScreen().bounds)
    window.rootViewController = vc
    window.makeKeyAndVisible()

    vc.loadView()
}
Run Code Online (Sandbox Code Playgroud)