class SendHelloWorker(
private val context: Context,
params: WorkerParameters
) : CoroutineWorker(context, params) {
override suspend fun doWork(): Result {
val name = inputData.getString("name") ?: return Result.failure()
val api = (context.applicationContext as MyApplication)
.appComponent
.api()
return try {
api.sendHello("Hello $name")
Result.success()
} catch (e: Exception) {
Result.failure()
}
}
}
まず CoroutineWorker や Worker をテストするには worker-testing artifact を使います。
testImplementation "androidx.work:work-testing:$work_version"
CoroutineWorker のテストには TestListenableWorkerBuilder を使います。
TestListenableWorkerBuilder は version 2.1.0 から追加されています。
TestListenableWorkerBuilder の build() で Worker のインスタンスを取得し、doWork() を呼んで結果をチェックします。
class SendHelloWorkerTest {
private lateinit var api: MyApi
private lateinit var context: Context
@Before
fun setup() {
api = mock()
val appComponent: AppComponent = mock()
whenever(appComponent.api()).thenReturn(api)
val application = MyApplication()
application.setAppComponent(appComponent)
context = mock()
whenever(context.applicationContext).thenReturn(application)
}
@Test
fun doWork() {
val worker = TestListenableWorkerBuilder<SendHelloWorker>(
context,
inputData = Data.Builder()
.putString("name", "Android")
.build()
)
.build()
runBlocking {
val result = worker.doWork()
assertThat(result).isEqualTo(ListenableWorker.Result.success())
verify(api).sendHello("Hello Android")
}
}
@Test
fun doWork_fail() {
val worker = TestListenableWorkerBuilder<SendHelloWorker>(
context,
inputData = Data.Builder()
.putString("name", "Android")
.build()
)
.build()
whenever(api.sendHello("Hello Android")).thenThrow(RuntimeException())
runBlocking {
val result = worker.doWork()
assertThat(result).isEqualTo(ListenableWorker.Result.failure())
verify(api).sendHello("Hello Android")
}
}
}
CoroutineWorker ではなく Worker をテストするときは TestListenableWorkerBuilder ではなく TestWorkerBuilder を使います。
参考 : https://developer.android.com/topic/libraries/architecture/workmanager/how-to/testing-worker-impl
0 件のコメント:
コメントを投稿