【发布时间】:2019-08-03 21:13:35
【问题描述】:
不过可能是重复的;接受的答案没有回答我的问题: How to fake Realm Results for tests
在对我的视图控制器进行单元测试时,我想在我的模拟对象上返回一个虚假的 Realm 'Results' 对象。 (Similar to how it can be done with Moq in C#)
是否可以在不创建 In-Memory Realm 数据库、将所需数据添加到其中然后查询对象的情况下创建由我的测试数据组成的 Realm Results 对象?
模拟对象:
class MockRealmRepository: RealmRepository {
override init() {}
var getAccountRolesCallCount = 0
var getAccountRolesReturnValue: Results<AccountRole>!
override func getAccountRoles() -> Results<AccountRole> {
getAccountRolesCallCount += 1
return getAccountRolesReturnValue
}
}
Mock 的单元测试实现:
class CreateProfileViewControllerTests: XCTestCase {
private var mockRealmRepository: MockRealmRepository!
override func setUp() {
super.setUp()
mockRealmRepository = MockRealmRepository()
}
func testCheckUsersRole_Valid() {
let admin = AccountRole(role: "Admin")
let user = AccountRole(role: "User")
let guest = AccountRole(role: "Guest")
// Create a Results<AccountRole>() containing the above AccountRole objects
mockRealmRepository.getAccountRolesReturnValue = // Assign my Results<AccountRole> object here
}
}
【问题讨论】: