【问题标题】:Testing more than one function with Room in JUnit在 JUnit 中使用 Room 测试多个功能
【发布时间】:2021-02-05 14:02:59
【问题描述】:

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

我在互联网上找不到任何解决方案。

这是我的测试课:

@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())
}
}

【问题讨论】:

    标签: android unit-testing kotlin junit android-room


    【解决方案1】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-24
      • 1970-01-01
      相关资源
      最近更新 更多