单元测试用例视图控制器崩溃迅速

时间:2015-01-07 06:10:17

标签: unit-testing swift ios8

我正在为iOS应用中的视图控制器编写单元测试用例。我试图测试涉及IBOutlets的UI元素是否不是如下代码中的nil。

class ClientsViewControllerTests: XCTestCase {

var clientsVC: ClientsTableViewController?

override func setUp() {
    super.setUp()

    let storyboard = UIStoryboard(name: "Clients", bundle: nil)

    clientsVC = storyboard.instantiateInitialViewController() as? ClientsTableViewController

    if let vc = clientsVC?{
        vc.loadView()
    }
}

override func tearDown() {

    super.tearDown()
    clientsVC = nil
}

func testClientViewControllerNotNil(){

    XCTAssertNotNil(clientsVC, "view controller cannot be nil")
}

我测试失败并输出"view controller cannot be nil"

我不明白为什么。但是,下面的测试通过了:

func testStoryBoard(){
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    var vc = storyboard.instantiateViewControllerWithIdentifier("MainVC") as UIViewController
    XCTAssertNotNil(vc,"Storyboard is not connected with a viewcontroller")

但是我需要在第一种方法中执行它,因为我想测试特定viewController的IBOutlet绑定,如:

XCAssertNotNil(vc.sendButton, "Send button is nil")

请指导我为什么测试失败以及如何在ViewControllers中测试插座绑定和动作绑定

2 个答案:

答案 0 :(得分:2)

经过大量试用n错误,我们发现以下代码适用于我们。问题是我们在bundle参数中传递'nil'值。当这被替换为以下行时,它开始起作用。 bundle: NSBundle(forClass: self.dynamicType))

工作代码:

let storyboard = UIStoryboard(name: "Clients", bundle: NSBundle(forClass: self.dynamicType))

var vc = storyboard.instantiateViewControllerWithIdentifier("ClientsVCTable") as ClientsTableViewController

vc.loadView()

XCTAssertNotNil(vc.clientSearchBar,"Not Nil")

同样适用于IBActions:

let storyboard = UIStoryboard(name: "Login", bundle: NSBundle(forClass: self.dynamicType))

var vc = storyboard.instantiateViewControllerWithIdentifier("LoginViewController") as LoginViewController

vc.loadView()

let actions : NSArray = vc.signInButton.actionsForTarget(vc, forControlEvent: UIControlEvents.TouchUpInside)!

XCTAssertTrue(actions.containsObject("login"), "IBActions not found")

答案 1 :(得分:0)

在setUp方法中放置一个断点来检查clientsVC对象是否已初始化。尝试 instantiateViewControllerWithIdentifier (“Client”)方法进行初始化。

请记住,setUp和tearDown方法将分别在类中的每个测试方法执行之前和之后调用。