Google se compromete a impulsar la igualdad racial para las comunidades afrodescendientes. Obtén información al respecto.

Cómo probar una implementación de trabajadores

A partir de la versión 2.1.0, WorkManager proporciona API para probar Worker, ListenableWorker y las variantes de ListenableWorker (CoroutineWorker y RxWorker).

Antes de la versión 2.1.0, para probar tus trabajadores, tenías que usar WorkManagerTestInitHelper a fin de inicializar WorkManager. Con la versión 2.1.0, no necesitas usar WorkManagerTestInitHelper cuando pruebas la implementación de Worker.

Cómo probar ListenableWorker y sus variantes

Para probar un ListenableWorker o sus variantes (CoroutineWorker y RxWorker), usa TestListenableWorkerBuilder. Este compilador ayuda a compilar instancias de ListenableWorker que se pueden usar para probar la lógica empresarial de Worker.

Por ejemplo, supongamos que necesitamos probar un CoroutineWorker que se ve de la siguiente manera:

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());
                }
            }
        }
    }

    

Para probar SleepWorker, primero creamos una instancia del trabajador con TestListenableWorkerBuilder. Este compilador también se puede usar para configurar etiquetas, inputData, runAttemptCount, etc. Para obtener más información, consulta la página de referencia de 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()));
        }
    }
    

Cómo probar a los trabajadores

Supongamos que tenemos un elemento Worker que se ve de la siguiente manera:

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();
        }
    }

    

Para probar este elemento Worker, ahora puedes usar TestWorkerBuilder. La diferencia principal entre TestWorkerBuilder y un TestListenableWorkerBuilder es que TestWorkerBuilder te permite especificar el Executor en segundo plano que se usa para ejecutar el elemento 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()));
        }
    }