问题
Using the JUnit4 Test Runner, the test runs and seems to work, but the query returns no results:
@RunWith(AndroidJUnit4::class)
class LocationViewInstrumentationTest {
@Rule
public val mActivityRule: ActivityTestRule<MapsActivity> = ActivityTestRule(MapsActivity::class.java)
@Rule
var testFolder = TemporaryFolder()
@Test
fun mapViewIsRendered() {
onView(withId(R.id.map)).check(matches(isDisplayed()))
}
@Test
@Throws(IOException::class)
fun canSaveLocation() {
val tempFolder = testFolder.newFolder("realmdata")
val config = RealmConfiguration.Builder(tempFolder).build()
val realm = Realm.getInstance(config)
realm.beginTransaction()
val location = Location("Poppy Manor", 33.2, -121.3, 0.0)
assertThat(location, not(nullValue()))
realm.commitTransaction()
RealmQuery<Location> query = realm.where(Location.class);
RealmResults<Location> results = query.findAll();
assertThat(results.size(), equalTo(1));
}
Yes I looked at the example project but do not want to add all the dependencies and want my tests to be readable so trying to avoid all the mocks too.
回答1:
You didn't write to the Realm in the transaction.
Try to add realm.copyToRealm(location)
before realm.commitTransaction()
.
来源:https://stackoverflow.com/questions/36253617/issue-with-realm-unit-test-on-android