Android:Roboeletic测试从应用程序抛出错误,onCreate

jobtbby3  于 2022-12-09  发布在  Android
关注(0)|答案(1)|浏览(97)

当尝试启动我的一个测试时,Robolectric抛出一个错误,说我的自定义Application Class中的一个变量没有初始化(kotlin.UninitializedPropertyAccessException: lateinit property workerList has not been initialized)。这可能是因为我的lateinit属性workerList稍后将用dagger-hilt初始化。

应用程序类

@HiltAndroidApp
@InternalCoroutinesApi
class App : Application(), Configuration.Provider {
    @Inject lateinit var workerFactory: HiltWorkerFactory
    @Inject lateinit var workerList: WorkerList // this causes the problem
    override fun onCreate() {
        super.onCreate()
        plantTimberTree()
        workerList.startDownloadDocumentWork() // this causes the problem
    }

    override fun getWorkManagerConfiguration(): Configuration =
        Configuration.Builder().setWorkerFactory(workerFactory).build()
}

当删除workerList.startDownloadDocumentWork()时,我的所有测试用例都能重新工作。我如何在不删除workerList.startDownloadDocumentWork()的情况下以某种方式解决问题?

堆栈跟踪

kotlin.UninitializedPropertyAccessException: lateinit property workerList has not been initialized

    at com.example.app.App.onCreate(App.kt:21)
    at org.robolectric.android.internal.AndroidTestEnvironment.lambda$installAndCreateApplication$0(AndroidTestEnvironment.java:288)
    at org.robolectric.util.PerfStatsCollector.measure(PerfStatsCollector.java:75)
    at org.robolectric.android.internal.AndroidTestEnvironment.installAndCreateApplication(AndroidTestEnvironment.java:288)
    at org.robolectric.android.internal.AndroidTestEnvironment.setUpApplicationState(AndroidTestEnvironment.java:171)
    at org.robolectric.RobolectricTestRunner.beforeTest(RobolectricTestRunner.java:319)
    at org.robolectric.internal.SandboxTestRunner$2.lambda$evaluate$0(SandboxTestRunner.java:254)
    at org.robolectric.internal.bytecode.Sandbox.lambda$runOnMainThread$0(Sandbox.java:89)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
k4emjkb1

k4emjkb11#

如果使用Robolectric进行测试时不需要这些行,则可以创建一个自定义应用程序类并将其用于Robolectric。
class TestApp : Application()
在测试中添加:@Config(application = TestApp::class)

相关问题