1/* 2 * Copyright 2018 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package androidx.work.impl.utils.taskexecutor; 18 19import org.junit.rules.TestWatcher; 20import org.junit.runner.Description; 21 22/** 23 * A {@link org.junit.Rule} that swaps the background executor used by WorkManager with a 24 * different one which executes each task synchronously. 25 * Adapted from android arch core's InstantTaskExecutorRule. 26 */ 27 28public class InstantTaskExecutorRule extends TestWatcher { 29 @Override 30 protected void starting(Description description) { 31 super.starting(description); 32 WorkManagerTaskExecutor.getInstance().setTaskExecutor(new TaskExecutor() { 33 @Override 34 public void postToMainThread(Runnable r) { 35 r.run(); 36 } 37 38 @Override 39 public void executeOnBackgroundThread(Runnable r) { 40 r.run(); 41 } 42 }); 43 } 44 45 @Override 46 protected void finished(Description description) { 47 super.finished(description); 48 WorkManagerTaskExecutor.getInstance().setTaskExecutor(null); 49 } 50} 51