mercredi 5 août 2015

XCT Testing of IBActions and IBOutlets Swift (Optionals)

I am wondering what is the best way to test IBOutlets and IBActions in Swift due to IBActions being Optionals.

I am currently rewriting a project I originally wrote in Swift but this time I want to use XCT Unit Testing.

I have already run into a small problem regarding the testing of IBOutlets and IBActions. Here is my code:

override func setUp() {
    super.setUp()

    storyboard = UIStoryboard(name: "Main", bundle: nil)
    mainMenuViewController = storyboard.instantiateViewControllerWithIdentifier("MainMenuViewController") as! MainMenuViewController

    let dummy = mainMenuViewController.view // force loading subviews and setting outlets

    mainMenuViewController.viewDidLoad()
}

override func tearDown() {
    // Put teardown code here. This method is called after the invocation of each test method in the class.
    super.tearDown()
}

func testWhetherTranslationGameModeButtonExists() {
    XCTAssert(mainMenuViewController.translateButton != nil, "translate button should exist at all times");
}

func testWhetherTranslateGameModeButtonTitleIsCorrect() {

    let title: String? = mainMenuViewController.translateButton?.titleLabel?.text

    if let unwrappedTitle = title {
        XCTAssertTrue(unwrappedTitle == "Translate Mode", "title of translate button should be Translate Mode")
    }
    else {
        XCTFail("Value isn't set")
    }
}

func testTranslateGameModeButtonIBAction() {

    if let unwrappedButton = mainMenuViewController.translateButton {
        if let actions: Array<String> = unwrappedButton.actionsForTarget(mainMenuViewController, forControlEvent: UIControlEvents.TouchUpInside) as? Array<String> {

            contains(actions, "")
            XCTAssertTrue(contains(actions, "translateButtonPressed"), "translate button should call method translateButtonPressed")
        }
        else {
            XCTFail("button is set but the IBAction is not set")
        }
    }
    else {
        XCTFail("button isn't set and therefore IBAction can not function")
    }
}

As you can see, the first test checks to see whether the translate game mode button exists. This works fine.

However with the title test I need to unwrap the button and then test the label. This seems like two tests in one.

I have the same issue when it comes to the IBAction. I need to unwrap the optional type to use the button and have a XCTAssert for the success and the failure. Therefore every time I use this button I will need to unwrap it before I can use it. This seems very repetitive and again seems like multiple tests in one.

I am wondering if this is the correct approach, or is there a better way to approach the testing of optionals.

Aucun commentaire:

Enregistrer un commentaire