在Android下测试Realm [英] Testing Realm under Android
问题描述
我有一个Android应用程序,我使用Realm来保存数据。我现在想要使用Realm为这个应用程序编写单元测试。
I have an application for Android where I use Realm to persist data. I now want to write a unit test for this application, utilizing Realm.
但是,我不希望单元测试干扰我现有的Realm数据。所以我想为我的测试实例生成不同的Realm文件。我不在乎他们是否有不同的名称,或者存储在不同的目录中。
However, I do not want the unit test to interfere with my existing Realm data. So I want to generate different Realm files for my test Instance. I don't care if they have a different name, or are stored in a different directory.
我试图使用 RenamingDelegatingContext
,但没有成功。根据 https://groups.google.com/forum/ #!msg / realm-java / WyHJHLOqK2c / WJFYvglIGk0J getInstance()
仅使用上下文
来调用 getFilesDir()
,它似乎没有覆盖 getFilesDir()
方法,所以我最终使用了我的直播用于测试的数据。
I have tried to use a RenamingDelegatingContext
, but with no success. According to https://groups.google.com/forum/#!msg/realm-java/WyHJHLOqK2c/WJFYvglIGk0J getInstance()
only uses the Context
to call getFilesDir()
, which does not seem to be overwriting the getFilesDir()
method, so I end up using my live data for testing.
接下来我尝试使用 IsolatedContext
,但是 IsolatedContext.getFilesDir()
返回 null
,所以这也没有成功。
Next I tried to use IsolatedContext
, but IsolatedContext.getFilesDir()
returns null
, so this also was not successful.
最后,我试着写一堂课扩展 RenamingDelegatingContext
,覆盖 getFilesDir()
,返回Realm使用的其他目录。我使用AndroidStudio的DeviceMonitor创建了目录,但是当我尝试使用此上下文时,Realm失败并出现 io.realm.exceptions.RealmIOException:无法打开。没有权限。 open()失败:权限被拒绝
。
Finally, I tried to write a class extending RenamingDelegatingContext
, overwriting getFilesDir()
, return a different directory for Realm to use. I created the directory using the DeviceMonitor of AndroidStudio, but when I try to use this context, Realm fails with an io.realm.exceptions.RealmIOException: Failed to open . Permission denied. open() failed: Permission denied
.
有没有人知道是否有可能在不影响实时数据的情况下测试Realm?
Does anyone know if there is a possibility to test Realm without affecting live data?
推荐答案
我实际上非常盲目,只需在测试设置期间为RealmDatabase使用不同的名称,同时生成其配置,该解决方案非常简单。我的解决方案现在看起来如下:
I was actually quite blind, with the solution being quite easy by just using a different name for the RealmDatabase during test setup while generating its configuration. My solution now looks as follows:
RealmConfiguration config = new RealmConfiguration.Builder(getContext()).
schemaVersion(1).
migration(new CustomMigration()).
name("test.realm").
inMemory().
build();
Realm.setDefaultConfiguration(config);
这篇关于在Android下测试Realm的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!