Unit testing : Warning Presenting View on View whose View is not in window hierachy

Viewed 1296

I have a UIViewController with a UICollectionView of which is not the root my app but is reached via a segue. This UICollectionView has UICollectionViewCells having an imageView with a UITapGestureRecognizer that when triggered helps present a UIAlertViewController. I have been having troubles testing my show alert method as I get this warning :

"Attempt to present on * whose view is not in the window hierarchy!"

The snippet of my code is written below

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?)
}
}

A snippet of the real function in by view controller is as follows

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 Answers
Related