简体   繁体   中英

Testing more than one function with Room in JUnit

i am doing some tests in my android application. The app uses Room for data storage and now i am writing some tests to test the Data Access Object function. My problem is that i cant run more than one test each time, cause it give my this error: Cannot perform this operation because the connection pool has been closed .

I couldnt find any solution on Internet.

Here is my test 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())
}
}

I'm not familiar with the MeteofyDatabase.getDatabaseInstance function, and could not find any references to it, other than in this question.

However, could it be that you're using the same static reference throughout your tests? This would cause you to close your database and then try to reuse the same one on the next test.

You could try to replace the MeteofyDatabase.getDatabaseInstance call with this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM