英文:
Get applicationContext in JUnit tests for RoomDB
问题
I can help you with the translation. Here's the translated code portion you provided:
无法在测试中获取应用程序上下文以创建 Room 数据库
@RunWith(AndroidJUnit4::class)
//@RunWith(RobolectricTestRunner::class)
class AppDatabaseTest {
private lateinit var context: Context
private lateinit var database: AppDatabase
@Test
fun someTest() {
context = ApplicationProvider.getApplicationContext()
// RuntimeEnvironment.getApplication()
database = Room.inMemoryDatabaseBuilder(
context,
AppDatabase::class.java
).build()
assertEquals(2, 1+1)
}
}
异常信息如下:
尝试使用 ApplicationProvider.getApplicationContext()
时,出现以下异常:
未注册测试框架!必须在已注册测试框架下运行。
java.lang.IllegalStateException: 未注册测试框架!必须在已注册测试框架下运行。
at androidx.test.platform.app.InstrumentationRegistry.getInstrumentation(InstrumentationRegistry.java:45)
at androidx.test.core.app.ApplicationProvider.getApplicationContext(ApplicationProvider.java:41)
at com.olexii8bit.notesapp.data.room.AppDatabaseTest.someTest(AppDatabaseTest.kt:19)
尝试使用 RuntimeEnvironment.getApplication()
(来自 Robolectric)时,也会引发以下异常:
getApplication(...) 不得为 null
java.lang.NullPointerException: getApplication(...) 不得为 null
at com.olexii8bit.notesapp.data.room.AppDatabaseTest.someTest(AppDatabaseTest.kt:20)
请问我还可以为您提供其他帮助吗?
英文:
I cant get application context to create Room database in tests
@RunWith(AndroidJUnit4::class)
//@RunWith(RobolectricTestRunner::class)
class AppDatabaseTest {
private lateinit var context: Context
private lateinit var database: AppDatabase
@Test
fun someTest() {
context = ApplicationProvider.getApplicationContext()
// RuntimeEnvironment.getApplication()
database = Room.inMemoryDatabaseBuilder(
context,
AppDatabase::class.java
).build()
assertEquals(2, 1+1)
}
}
When i tried to acheave that by ApplicationProvider.getApplicationContext()
it falls with next exception
No instrumentation registered! Must run under a registering instrumentation.
java.lang.IllegalStateException: No instrumentation registered! Must run under a registering instrumentation.
at androidx.test.platform.app.InstrumentationRegistry.getInstrumentation(InstrumentationRegistry.java:45)
at androidx.test.core.app.ApplicationProvider.getApplicationContext(ApplicationProvider.java:41)
at com.olexii8bit.notesapp.data.room.AppDatabaseTest.someTest(AppDatabaseTest.kt:19)
And I tried RuntimeEnvironment.getApplication()
from Robolectric but it also throws an exception
getApplication(...) must not be null
java.lang.NullPointerException: getApplication(...) must not be null
at com.olexii8bit.notesapp.data.room.AppDatabaseTest.someTest(AppDatabaseTest.kt:20)
What am i doing wrong?
答案1
得分: 0
解决方案是在androidTest
模块中创建测试,而不是在unitTest
中。
然后,您将能够使用上下文,使用InstrumentationRegistry.getInstrumentation().targetContext
。
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论