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

时间:2016-03-18 13:33:46

标签: ios swift unit-testing

我有一个UIViewController,其UICollectionView不是我的应用程序的根,但是通过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?)
}
}

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

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)

}

1 个答案:

答案 0 :(得分:2)

您的视图控制器不在窗口中,因此无法显示另一个视图控制器。您应该可以使用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()
}