gpt4 book ai didi

unit-testing - 单元测试用例 View Controller 崩溃 swift

转载 作者:可可西里 更新时间:2023-11-01 01:42:41 24 4
gpt4 key购买 nike

我正在为我的 iOS 应用程序中的 View Controller 编写单元测试用例。我正在尝试测试涉及 IBOutlets 的 UI 元素是否不像下面的代码那样为零。

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 绑定(bind),例如:

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

请指导我测试失败的原因以及如何测试 ViewController 中的导出绑定(bind)和 Action 绑定(bind)

最佳答案

经过多次试错,我们发现以下代码对我们有效。问题是我们在 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")

关于unit-testing - 单元测试用例 View Controller 崩溃 swift ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27813413/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com