Testing Realm with XCTest (Swift)

Goof day,

Anyone here knows how I can access Realm objects in XCTest? I have replaced the default realm file with a pre-populated one. I can see that the data is there through Realm Studio but everytime I access the objects, it’s nil.

Here’s what I got so far. Where LineItem object count is always 0.

class CountTests: XCTestCase {

var defaultRealmPath: URL!
var realm: Realm!

override func setUp() {
    super.setUp()
    
    let path = Bundle.main.path(forResource: "count", ofType: "realm") ?? ""
    let realmURL = URL(fileURLWithPath: path)
    
    _ = try! FileManager.default.replaceItemAt(Realm.Configuration.defaultConfiguration.fileURL!, withItemAt: realmURL)
    defaultRealmPath = Realm.Configuration.defaultConfiguration.fileURL!
    
    let config = Realm.Configuration(fileURL: defaultRealmPath)
    realm = try! Realm(configuration: config)
}

override func tearDown() {
    super.tearDown()
    
    try! FileManager.default.removeItem(at: Realm.Configuration.defaultConfiguration.fileURL!)
    realm = nil
}

func test_scan10012_willIncreaseCount() {
    
    XCTAssertEqual(realm.objects(LineItem.self).count, 40)
    
    let countSession = CountSession()
    CountTests.productScanned("10012", countSession: countSession)

    XCTAssertEqual(realm.objects(LineItem.self).count, 41)
}

}

@Lie-an We use XCTest extensively in our RealmSwift binding - you can see a ton of examples here:

1 Like