【问题标题】:How to create fake Realm results for unit tests如何为单元测试创​​建假 Realm 结果
【发布时间】: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

        }
    }

【问题讨论】:

    标签: ios swift xcode realm


    【解决方案1】:

    我可能会创建一个用于测试的 InMemory 领域并将其注入到您的测试中。

    基本上你会:

    1. 在内存中创建领域
    2. 将三个角色添加到内存领域
    3. 使用普通的realm.objects(AccountRole.self)

    【讨论】:

    • 是不是因为没有先将 Result 对象存储在 InMemory 数据库中并获取它们就无法创建它们?
    • 我不确定这是不可能的,但这里的答案 (stackoverflow.com/questions/38902475/…) 确实说它无法完成。我只是认为这是最好的方法,因为它可以通过 Realm 集成为您提供准确的系统测试,并且您不必担心模拟所有功能或结果。可能不是唯一的方法,但它简单、干净、快速。
    • 很抱歉,您现在正在特别询问是否可以在没有内存数据库的情况下执行此操作。猜猜我的回答并没有真正回答你想要的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多