不要测试您的UIViewControllers。有很多事情发生在他们身上,你看不到和/或无法控制。相反,在其他对象(例如视图模型)中保留尽可能多的逻辑,而不是您的 UIViewControllers。然后您可以测试您的视图模型,就像您测试您的模型一样。
编辑:
您可能希望如何构建 UIViewControllers 并测试模型和查看模型:
这段代码的主要内容是:
- 使用Dependency Injection
- 在 Release 中为类提供真实的依赖关系,在测试中为类提供虚假的依赖关系
视图控制器
// this class is super simple, so there's hardly any reason to test it now.
class SomeViewController: UIViewController {
@IBOutlet weak var someLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// we give the *real* user accessor in the view controller
let viewModel = SomeViewModel(userAccessor: DBUserAccessor())
someLabel.text = viewModel.welcomeMessage
}
}
用户模型
struct User {
var name: String
}
用户访问器
这是您的视图模型需要的一些依赖项。在发布期间提供一个真实的(在您的视图控制器中)。在测试的时候给一个假的,这样你就可以控制它了。
protocol UserAccessor {
var currentUser: User? { get }
}
// since we're using the fake version of this class to test the view model, you might want to test this class on its own
// you would do that using the same principles that I've shown (dependency injection).
class DBUserAccessor: UserAccessor {
var currentUser: User? {
// some real implementation that's used in your app
// get the user from the DB
return User(name: "Samantha") // so not really this line, but something from CoreData, Realm, etc.
}
}
class FakeUserAccessor: UserAccessor {
// some fake implementation that's used in your tests
// set it to whatever you want your tests to "see" as the current User from the "DB"
var currentUser: User?
}
查看模型
这是您要测试的实际逻辑所在的位置。
class SomeViewModel {
let userAccessor: UserAccessor
init(userAccessor: UserAccessor) {
self.userAccessor = userAccessor
}
var welcomeMessage: String {
if let username = self.username {
return "Welcome back, \(username)"
} else {
return "Hello there!"
}
}
var username: String? {
return userAccessor.currentUser?.name
}
}
测试
最后,你想如何测试它。
class SomeViewModelTest: XCTestCase {
func testWelcomeMessageWhenNotLoggedIn() {
let userAccessor = FakeUserAccessor()
let viewModel = SomeViewModel(userAccessor: userAccessor) // we give the *fake* user accessor to the view model in tests
userAccessor.currentUser = nil // set the fake UserAccessor to not have a user "logged in"
// assert that the view model, which uses whatever you gave it, gives the correct message
XCTAssertEqual(viewModel.welcomeMessage, "Hello there!")
}
func testWelcomeMessageWhenLoggedIn() {
let userAccessor = FakeUserAccessor()
let viewModel = SomeViewModel(userAccessor: userAccessor)
userAccessor.currentUser = User(name: "Joe") // this time, the use is "logged in"
XCTAssertEqual(viewModel.welcomeMessage, "Welcome back, Joe") // and we get the correct message
}
}