Reputation: 8552
I've got a series of individual XCTest
unit tests that each run a JSON parsing function - as part of the parsing, any instances of a Realm object class that exist are deleted, before they are recreated based on the JSON that is being handled.
In the setup()
function of each test class, the Realm instance is being setup with this:
Realm.Configuration.defaultConfiguration.inMemoryIdentifier = NSUUID().UUIDString
do {
realm = try Realm()
} catch let error as NSError {
// handle error
fatalError("Unable to establish Realm stack: \(error.localizedDescription)")
}
// Clear Realm of everything
try! realm.write {
realm.deleteAll()
}
As I understand things, this should create a completely unique and empty Realm instance for each test.
Running each test class individually works fine, but when run as part of the full test suite a random selection of tests fail with an error:
caught "RLMException", "Object has been deleted or invalidated."
I assume this is because there's a race condition somewhere when all the test classes are run simultaneously as part of the test target. That raises three questions:
UPDATE Separating out the clashing test into a separate test target prevents the clash, but that's not really an optimal solution.
Upvotes: 1
Views: 1603
Reputation: 14409
Instead of mutating the default configuration, could you try setting it?
var uniqueConfiguration = Realm.Configuration.defaultConfiguration
uniqueConfiguration.inMemoryIdentifier = NSUUID().UUIDString
Realm.Configuration.defaultConfiguration = uniqueConfiguration
If this works, I'd qualify the current Realm behavior as a bug.
Upvotes: 1
Reputation: 1787
The official documentation for Realm Swift recommends that each test configure the default Realm to use a unique file (https://realm.io/docs/swift/latest/#configuring-the-default-realm). This should satisfy your second question, and at the very least prevent errors from unit tests scribbling upon each others' shared state.
Upvotes: 0