2

Maybe a duplicate, however; the accepted answer did not answer my question: How to fake Realm Results for tests

I want to return a fake Realm 'Results' object on my mocked object when unit testing my View Controller. (Similar to how it can be done with Moq in C#)

Is it possible to create a Realm Results object consisting of my test data without creating an In-Memory Realm database, adding the required data into it & then querying it for the objects?

Mock Object:

class MockRealmRepository: RealmRepository {

    override init() {}

    var getAccountRolesCallCount = 0
    var getAccountRolesReturnValue: Results<AccountRole>!


    override func getAccountRoles() -> Results<AccountRole> {
        getAccountRolesCallCount += 1
        return getAccountRolesReturnValue
    }
}

Unit Test implementation of 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

        }
    }
Anjali Kevadiya
  • 3,567
  • 4
  • 22
  • 43
Alex Marchant
  • 570
  • 6
  • 21

1 Answers1

1

I would probably create an InMemory realm for testing and inject that into your tests.

Basically you would:

  1. Create a realm in memory
  2. Add the three roles to the in memory realm
  3. Use a normal realm.objects(AccountRole.self)
GBreen12
  • 1,832
  • 2
  • 20
  • 38
  • Is that because there is no way of creating the Result object without first storing them in the InMemory database and getting them? – Alex Marchant Aug 08 '19 at 11:06
  • 1
    I'm not sure about it being impossible but the answer here (https://stackoverflow.com/questions/38902475/how-to-fake-realm-results-for-tests?rq=1) does say it can't be done. I just think it's the best way because it will give you an accurate test of your system with Realm integration and you wouldn't have to worry about mocking all the functionality or Results. Might not be the only way but it's simple, clean and fast. – GBreen12 Aug 08 '19 at 14:26
  • Sorry just seeing now that you're asking specifically about the possibility of doing it without an in memory database. Guess my answer doesn't really answer what you want. – GBreen12 Aug 08 '19 at 14:30