gpt4 book ai didi

ios - 在测试中实例化 UIViewController

转载 作者:行者123 更新时间:2023-11-28 08:51:39 26 4
gpt4 key购买 nike

我在 Swift 2 中工作,想在我的 View Controller 中测试功能。我做了一个类似依赖注入(inject)的服务,看起来像这样:

extension UIViewController: {
func getDbService() -> IDbService {
let context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
return DbService(context: context)
}
}

有了这个,我可以将 AppDelegate 的上下文设置为模拟上下文以用于测试目的。但是,当我尝试实例化 View Controller 时出现问题。这是代码:

class LoginViewController: UIViewController {
var token: String?

override func viewDidLoad() {
super.viewDidLoad()
let dbService = getDbService()
self.token = dbService.getToken()
//....do stuff with token
}
}

我像这样实例化测试:

class LoginViewControllerTests: XCTestCase {
func testTokenExists() {
let mockContext = MockContextUtils.getMockContext()
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.managedObjectContext = mockContext
let sut = LoginViewController()
let _ = sut.view // Apparently this renders the view; I set a breakpoint, viewDidLoad is called
XCTAssertNotNil(sut.token) // FAILS, BECAUSE APPDELEGATE CALLS APP DATABASE, AND NOT MOCK.
}
}

这个简单测试失败的原因是 LoginViewController 不知道应用委托(delegate)是什么。有没有办法在初始化阶段引入它?

最佳答案

因此,使用默认 Controller 初始化 View Controller 似乎并没有获取我们在测试中设置的应用委托(delegate)。相反,我已经通过 Storyboard通过这样初始化了 View Controller :

let storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
let sut = storyboard.instantiateInitialViewController() as? LoginViewController
XCTAssertNotNil(sut)
XCTAssertNotNil(sut.view)
XCTAssertNotNil(sut.token)

解决了这个问题。

关于ios - 在测试中实例化 UIViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34034985/

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