为仪表测试实例化Hilt Worker ?



我在试图初始化我的WorkerGetData类进行仪器测试时遇到了问题。我做了以下的事情:

  1. 删除manifest文件中的默认工作初始化项。
  2. Application类中增加配置提供程序。
  3. 在Test文件中调用WorkManagerTestInitHelper
  4. 添加kapt "androidx.hilt:hilt-compiler:1.0.0"到app模块
  5. 添加kapt "com.google.dagger:hilt-compiler:2.42"到app模块

但仍然得到错误java.lang.NoSuchMethodException: com.example.myproject.WorkerGetData.<init> [class android.content.Context, class androidx.work.WorkerParameters]

我正在使用工作管理器版本2.7.1

<标题>代码
<provider
android:name="androidx.startup.InitializationProvider"
android:authorities="${applicationId}.androidx-startup"
android:exported="false"
tools:node="merge">
<meta-data
android:name="androidx.work.WorkManagerInitializer"
android:value="androidx.startup"
tools:node="remove" />
</provider>
@HiltAndroidApp
class Application : android.app.Application(), Configuration.Provider {
@Inject
lateinit var workerFactory: HiltWorkerFactory
override fun getWorkManagerConfiguration() =
Configuration.Builder()
.setWorkerFactory(workerFactory)
.build()
override fun onCreate() {
super.onCreate()
}
}
@HiltWorker
class WorkerGetData @AssistedInject constructor(
val repository: MyRepository,
@Assisted val context: Context,
@Assisted workerParameters: WorkerParameters,
): CoroutineWorker(context, workerParameters) {
override suspend fun doWork(): Result {
val data = repository.getData()
return Result.success(data)
}
}
@Test
fun testGetDataWorker() {
val request = OneTimeWorkRequestBuilder<WorkerGetData>()
.build()

val workManager = WorkManager.getInstance(context)
workManager.enqueue(request).result.get() /*<-----------------------error here*/

val workInfo = workManager.getWorkInfoById(request.id).get()
assertThat(workInfo.state).isEqualTo(WorkInfo.State.SUCCEEDED)
}

还有第六项我忘了做。我需要创建一个WorkerFatory(),以便Hilt可以正确地注入WorkerGetData构造函数。关于如何做到这一点,Pietro Maggi有一篇很棒的文章:

https://medium.com/androiddevelopers/customizing - workmanager和dagger- 1029688 c0978

相关内容

  • 没有找到相关文章

最新更新