Actually the question in the title arises when calling groupDao.insert(group1) .

JUnit code:

 @TestInstance(TestInstance.Lifecycle.PER_CLASS) class GroupUnitTest{ private lateinit var groupDao: GroupDao private lateinit var db: TournamentDatabase @BeforeAll fun createDb() { val context = mock(Context::class.java) db = Room.databaseBuilder( context, TournamentDatabase::class.java, "tournament") .allowMainThreadQueries() .build() groupDao = db.groupsDao() } @AfterAll @Throws(IOException::class) fun closeDb() { db.close() } @Test @Throws(Exception::class) fun writeAndReadInList() { val group1 = Group(null , "La Liga") groupDao.insert(group1) // This!!!!! val byName = groupDao.getGroupsByName(group1.name) assertThat(byName.get(0), equalTo(group1)) } 

}

The answer to my question: move the test to androidTest / java and write the code:

 @RunWith(AndroidJUnit4::class) class GroupTest{ private lateinit var groupDao: GroupDao private lateinit var db: TournamentDatabase @Before fun createDb() { val context = InstrumentationRegistry.getTargetContext() db = TournamentDatabase.getInstance(context)!! groupDao = db.groupsDao() } @After @Throws(IOException::class) fun closeDb() { db.close() } @Test @Throws(Exception::class) fun writeAndReadInList() { val group1 = Group(null , "La Liga") groupDao.insert(group1) val byName = groupDao.getGroupsByName(group1.name) assertThat(byName.get(0), equalTo(group1)) } } 
  • It was necessary to test the base in androidTest / Java in order to get a normal context through InstrumentationRegistry.getTargetContext (), and not in test / java, where unit testing is being conducted. - Vlad

0