我想知道在Swift中测试IBOutlets和IBActions的最佳方法,因为IBActions是可选的。
我目前正在重写一个我最初用Swift编写的项目,但这次我想使用XCT单元测试。
我已经遇到了一个小问题,涉及到对IBOutlets和IBActions进行测试。以下是我的代码:
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")
}
}
正如您所见,第一个测试检查翻译游戏模式按钮是否存在。这个测试很好用。
然而,在标题测试中,我需要展开按钮并测试标签。这似乎是两个测试。
当涉及IBAction时,我需要展开可选类型以使用按钮,并对成功和失败进行XCTAssert。因此,每次使用此按钮之前,我都需要展开它才能使用它。这似乎非常重复,再次看起来像多个测试。
我想知道这是否是正确的方法,或者有更好的方法来处理可选项的测试。