Bergabunglah bersama kami di ⁠#Android11: The Beta Launch Show pada tanggal 3 Juni!

Menguji implementasi Worker

Mulai versi 2.1.0, WorkManager menyediakan API untuk menguji varian Worker, ListenableWorker, dan ListenableWorker (CoroutineWorker dan RxWorker).

Sebelumnya pada versi 2.1.0, untuk menguji pekerja Anda harus menggunakan WorkManagerTestInitHelper untuk menginisialisasi WorkManager. Dengan versi 2.1.0, Anda tidak perlu menggunakan WorkManagerTestInitHelper jika Anda menguji implementasi Worker.

Menguji ListenableWorker dan variannya

Untuk menguji ListenableWorker atau variannya (CoroutineWorker dan RxWorker), gunakan TestListenableWorkerBuilder. Builder ini membantu membuat instance ListenableWorker yang dapat digunakan untuk keperluan pengujian logika bisnis Worker.

Misalnya, anggaplah kita perlu menguji CoroutineWorker yang terlihat seperti ini:

Kotlin

    class SleepWorker(context: Context, parameters: WorkerParameters) :
        CoroutineWorker(context, parameters) {
        override suspend fun doWork(): Result {
            delay(1000) // milliseconds
            return Result.success()
        }
    }

    

Java

    public class SleepWorker extends ListenableWorker {
        private final ResolvableFuture<Result> mResult;
        private final Handler mHandler;
        private final Object mLock;
        private Runnable mRunnable;
        public SleepWorker(
                @NonNull Context context,
                @NonNull WorkerParameters workerParameters) {
            super(context, workerParameters);
            mHandler = new Handler(Looper.getMainLooper());
            mResult = new ResolvableFuture<>();
            mLock = new Object();
        }

        @NonNull
        @Override
        public ListenableFuture<Result> startWork() {
            mRunnable = new Runnable() {
                @Override
                public void run() {
                    synchronized (mLock) {
                        mResult.set(Result.success());
                    }
                }
            };

            mHandler.postDelayed(mRunnable, 1000L);
            return mResult;
        }

        @Override
        public void onStopped() {
            super.onStopped();
            if (mRunnable != null) {
                mHandler.removeCallbacks(mRunnable);
            }
            synchronized (mLock) {
                if (!mResult.isDone()) {
                    mResult.set(Result.failure());
                }
            }
        }
    }

    

Untuk menguji SleepWorker, buat instance Worker terlebih dahulu menggunakan TestListenableWorkerBuilder. Builder ini juga dapat digunakan untuk menetapkan tag, inputData, runAttemptCount, dan sebagainya. Untuk detail selengkapnya, lihat halaman referensi TestListenableWorker.

Kotlin

    @RunWith(AndroidJUnit4::class)
    class SleepWorkerTest {
        private lateinit var context: Context

        @Before
        fun setUp() {
            context = ApplicationProvider.getApplicationContext()
        }

        @Test
        fun testSleepWorker() {
            // Kotlin code can use the TestListenableWorkerBuilder extension to
            // build the ListenableWorker
            val worker = TestListenableWorkerBuilder<SleepWorker>(context).build()
            runBlocking {
                val result = worker.doWork()
                assertThat(result, `is`(Result.success()))
            }
        }
    }

    

Java

    @RunWith(AndroidJUnit4.class)
    public class SleepWorkerJavaTest {
        private Context mContext;

        @Before
        public void setUp() {
            mContext = ApplicationProvider.getApplicationContext();
        }

        @Test
        public void testSleepWorker() throws Exception {
           ListenableWorker worker =
               TestListenableWorkerBuilder.from(mContext, SleepWorker.class)
                       .build();

            Result result = worker.startWork().get();
            assertThat(result, is(Result.success()));
        }
    }
    

Menguji Worker

Anggaplah kita memiliki Worker yang terlihat seperti ini:

Kotlin

    class SleepWorker(context: Context, parameters: WorkerParameters) :
        Worker(context, parameters) {

        companion object {
            const val SLEEP_DURATION = "SLEEP_DURATION"
        }

        override fun doWork(): Result {
            // Sleep on a background thread.
            val sleepDuration = inputData.getLong(SLEEP_DURATION, 1000)
            Thread.sleep(sleepDuration)
            return Result.success()
        }
    }

    

Java

    public class SleepWorker extends Worker {
        public static final String SLEEP_DURATION = "SLEEP_DURATION";

        public SleepWorker(
                @NonNull Context context,
                @NonNull WorkerParameters workerParameters) {
            super(context, workerParameters);
        }

        @NonNull
        @Override
        public Result doWork() {
            try {
                long duration = getInputData().getLong(SLEEP_DURATION, 1000);
                Thread.sleep(duration);
            } catch (InterruptedException ignore) {
            }
            return Result.success();
        }
    }

    

Untuk menguji Worker ini, kini Anda dapat menggunakan TestWorkerBuilder. Perbedaan utama antara TestWorkerBuilder dan TestListenableWorkerBuilder adalah, TestWorkerBuilder memungkinkan Anda menentukan latar belakang Executor yang digunakan untuk menjalankan Worker.

Kotlin

    // Kotlin code can use the TestWorkerBuilder extension to
    // build the Worker
    @RunWith(AndroidJUnit4::class)
    class SleepWorkerTest {
        private lateinit var context: Context
        private lateinit var executor: Executor

        @Before
        fun setUp() {
            context = ApplicationProvider.getApplicationContext()
            executor = Executors.newSingleThreadExecutor()
        }

        @Test
        fun testSleepWorker() {
            val worker = TestWorkerBuilder<SleepWorker>(
                context = context,
                executor = executor,
                inputData = workDataOf("SLEEP_DURATION" to 10000L)
            ).build()

            val result = worker.doWork()
            assertThat(result, `is`(Result.success()))
        }
    }

    

Java


    @RunWith(AndroidJUnit4.class)
    public class SleepWorkerJavaTest {
        private Context mContext;
        private Executor mExecutor;

        @Before
        public void setUp() {
            mContext = ApplicationProvider.getApplicationContext();
            mExecutor = Executors.newSingleThreadExecutor();
        }

        @Test
        public void testSleepWorker() {
            Data inputData = new Data.Builder()
                    .putLong("SLEEP_DURATION", 10_000L)
                    .build();

            SleepWorker worker =
                    (SleepWorker) TestWorkerBuilder.from(mContext,
                            SleepWorker.class,
                            mExecutor)
                            .setInputData(inputData)
                            .build();

            Result result = worker.doWork();
            assertThat(result, is(Result.success()));
        }
    }