Tuesday, 9 February 2021

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


from Testing more than one function with Room in JUnit

No comments:

Post a Comment