Frozen objects unit testing

We have unit tests in our project and, for each test, we create an in-memory realm, and when the test completes, we remove the realm instance and the folder containing that realm file.

We are implementing unit tests monitoring realm objects’ behavior when they are Frozen. The problem is that when the test completes, the app throws an exception telling me that “The realm file cannot be deleted because it is currently opened.” And the main cause of that behavior is realmEntity.Freeze() method. According to the documentation, whenever an object is frozen, it creates another instance of the “frozen” Realm that lives together with the original realm. Whenever the original realm is disposed and completely closed, the frozen Realm would close as well. However, this doesn’t happen immediately and if you try to delete the realm it will say there are open instances.

So the questions are following:

  1. How to delete the realm file in the tests containing frozen realm objects.
  2. How to unfreeze the frozen object?

That is correct, the frozen realm will be closed when the garbage collector collects the frozen objects. If you want to expedite the process, you can explicitly dispose it by accessing it via the Realm property on the object:

frozenObj.Realm.Dispose();

Regarding unfreezing - this is not currently supported, do you have a use case in mind where you need it? It’s not especially hard to add, just need to better understand the problem it solves.

1 Like

HI @nirinchev

Unfortunately, disposing of the frozen object’s realm does not help. I am getting the same exception as before when trying to delete the original realm database. Perhaps it keeps some references to the frozen object’s Realm even when I dispose and delete the frozen object’s Realm.

Regarding unfreezing - The reason for asking the unfreeze method is just to release the frozen object and release the frozen realm file to make it possible to delete the realm file.

I see, unfreezing won’t help in this case. I filed a bug report for the issue you’re seeing with disposing a frozen Realm. We’ll try to reproduce and report back.

1 Like

I have this hack/workaround in mind. I had kind of a similar problem one day (with something different) and when I used .Dispose() on something it didn’t work as intended but assigning null to the “object” (after disposing it!) solved the problem. Something with GC I think? I don’t remember exactly, though you may want to try it.

1 Like

Thank you @nirinchev for making an effort for it. I’ll continue the investigation.

Thank you @Michal_Kania for the workaround. I will try it.