gpt4 book ai didi

android - 使用 Workmanager 进行 Hilt Instrumentation 测试不工作

转载 作者:行者123 更新时间:2023-12-04 13:33:21 25 4
gpt4 key购买 nike

当我尝试在包含 WorkManager 的应用程序中运行 ActivityScenario 时,我在启动时收到以下错误:

java.lang.IllegalStateException: WorkManager is not initialized properly.  You have explicitly disabled WorkManagerInitializer in your manifest, have not manually called WorkManager#initialize at this point, and your Application does not implement Configuration.Provider.
使用 WorkManagerTestInitHelper来自 work-test神器也无济于事。
WorkManager 的定义如下:
@Provides
@Singleton
fun provideWorkmanager(@ApplicationContext context: Context) = WorkManager.getInstance(context)
这是我的测试自动取款机:
    @HiltAndroidTest
@RunWith(AndroidJUnit4::class)
class LoginTest {

@get:Rule(order = 0)
var hiltRule = HiltAndroidRule(this)

@get:Rule(order = 1)
val activityRule = ActivityScenarioRule(MainActivity::class.java)

@Before
fun before() {
val context = InstrumentationRegistry.getInstrumentation().targetContext
val config = Configuration.Builder()
.setMinimumLoggingLevel(Log.DEBUG)
.setExecutor(SynchronousExecutor())
.build()
WorkManagerTestInitHelper.initializeTestWorkManager(context, config)
}

@Test
fun test() {
...
}

}

最佳答案

这是因为 @get:Rule@Before 之前执行确实,根据 Google Documentation :

This rule provides functional testing of a single activity. The activity under test is launched before each test annotated with @Test and before any method annotated with @Before. It's terminated after the test is completed and all methods annotated with @After are finished. To access the activity under test in your test logic, provide a callback runnable to ActivityScenarioRule.getScenario().onActivity().


为了解决这个问题,您需要初始化 WorkManager在与 WorkManagerTestInitHelper 的测试中 之前 您尝试启动 Activity 。
为此,您应该避免使用 ActivityScenarioRule并使用 ActivityScenario相反,您可以执行以下操作:
@HiltAndroidTest
@RunWith(AndroidJUnit4::class)
class LoginTest {
private lateinit var scenario: ActivityScenario<MainActivity>

@get:Rule
var hiltRule = HiltAndroidRule(this)

@Before
fun before() {
val context = InstrumentationRegistry.getInstrumentation().targetContext
val config = Configuration.Builder()
.setMinimumLoggingLevel(Log.DEBUG)
.setExecutor(SynchronousExecutor())
.build()
WorkManagerTestInitHelper.initializeTestWorkManager(context, config)

scenario = launchActivity()
}

@Test
fun test() {
scenario.moveToState(Lifecycle.State.CREATED).onActivity {
activity -> // do some test with the activity
}
}
}

关于android - 使用 Workmanager 进行 Hilt Instrumentation 测试不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63671323/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com