在 JUnit 中使用 Room 测试多个功能

Testing more than one function with Room in JUnit

我正在 android 应用程序中进行一些测试。 该应用程序使用 Room 进行数据存储,现在我正在编写一些测试来测试数据访问对象功能。 我的问题是我每次不能 运行 多次测试,因为它给我这个错误:Cannot perform this operation because the connection pool has been closed.

我在 Internet 上找不到任何解决方案。

这是我的测试class:

@RunWith(RobolectricTestRunner::class)
@Config(maxSdk = Build.VERSION_CODES.P, minSdk = Build.VERSION_CODES.P)

class MeteofyDatabaseTest {

@get:Rule
val testRule = InstantTaskExecutorRule()

private lateinit var dao: WeatherPlaceDAO
private lateinit var appContext : Context
private lateinit var db : MeteofyDatabase

@Before
fun setup() {
    appContext = InstrumentationRegistry.getInstrumentation().targetContext
    MeteofyDatabase.TEST_MODE = true
    db = MeteofyDatabase.getDatabaseInstance(appContext)
    dao = db.weatherPlaceDAO()
}

@After
@Throws(IOException::class)
fun tearDown() {
    db.close()
}

@Test
fun insertAndRetrieveData() {
    val weatherPlace = WeatherPlace("test_place", "10", "Clouds")
    val testObserver = dao.getWeatherPlacesAsLiveData().test()
    dao.insertNewPlace(weatherPlace)
    Assert.assertTrue(testObserver.value()[0].placeName == weatherPlace.placeName)
}

//THIS GIVE ME THE ERROR
@Test
fun insertAndDeleteData(){
    val weatherPlace = WeatherPlace("test_place", "10", "Clouds")
    val testObserver = dao.getWeatherPlacesAsLiveData().test()
    dao.insertNewPlace(weatherPlace)
    dao.deleteByPlaceId(weatherPlace.placeName)
    Assert.assertTrue(testObserver.value().isEmpty())
}
}

我不熟悉 MeteofyDatabase.getDatabaseInstance 函数,除此问题外,找不到任何对它的引用。

但是,您是否在整个测试过程中使用了相同的静态引用? 这会导致您关闭数据库,然后尝试在下一次测试中重用同一个数据库。

您可以尝试将 MeteofyDatabase.getDatabaseInstance 调用替换为:

db = Room.inMemoryDatabaseBuilder(appContext, MeteofyDatabase::class.java).build()