Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ccabanero/a0fbb675f44a5136d2811d21a77e332a to your computer and use it in GitHub Desktop.
Save ccabanero/a0fbb675f44a5136d2811d21a77e332a to your computer and use it in GitHub Desktop.
Sample iOS Unit Tests: View Controller has segue
import XCTest
@testable import YourProjectModule
class ViewControllerTest: XCTestCase {
var systemUnderTest: ViewController!
override func setUp() {
super.setUp()
//get the storyboard the ViewController under test is inside
let storyboard: UIStoryboard = UIStoryboard(name: "Main_iPhone", bundle: nil)
//get the ViewController we want to test from the storyboard (note the identifier is the id explicitly set in the identity inspector)
systemUnderTest = storyboard.instantiateViewControllerWithIdentifier("ViewController") as! ViewController
//load view hierarchy
_ = systemUnderTest.view
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
// MARK: - Storyboard Segues
// utility for finding segues
func hasSegueWithIdentifier(id: String) -> Bool {
let segues = systemUnderTest.valueForKey("storyboardSegueTemplates") as? [NSObject]
let filtered = segues?.filter({ $0.valueForKey("identifier") as? String == id })
return (filtered?.count > 0) ?? false
}
func testSUT_HasSegue_ForTransitioningTo_ViewConrollerOne() {
let targetIdentifier = systemUnderTest.segueIdentifierName1 // segue identifier as a constant property of ViewController
XCTAssertTrue(hasSegueWithIdentifier(targetIdentifier))
}
func testSUT_HasSegue_ForTransitioningTo_ViewConrollerTwo() {
let targetIdentifier = systemUnderTest.segueIdentifierName2
XCTAssertTrue(hasSegueWithIdentifier(targetIdentifier))
}
}
// Unwind Segue Scenario ... inside ViewControllerTest that has an unwind segue
...
// MARK: - Navigation
// utility for finding segues
func hasSegueWithIdentifier(id: String) -> Bool {
let segues = systemUnderTest.valueForKey("storyboardSegueTemplates") as? [NSObject]
let filtered = segues?.filter({ $0.valueForKey("identifier") as? String == id })
return (filtered?.count > 0) ?? false
}
func testSUT_HasAnUnwindSegue() {
let targetIdentifier = systemUnderTest.segueIdentifierUnwindFromPlacesSearchViewController
XCTAssertTrue(hasSegueWithIdentifier(targetIdentifier))
}
...
// Unwind Segue Scenario ... inside ViewControllerTest that HANDLES the unwind segue
...
// MARK: - Navigation
func testSUT_HasUnwindAction_FromPlaceSearchViewController() {
XCTAssertTrue(systemUnderTest.respondsToSelector(#selector(systemUnderTest.unwindFromPlaceSearchViewController(_:))))
}
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment