• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2019 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 package org.chromium.base.task.test;
6 
7 import org.robolectric.annotation.Implementation;
8 import org.robolectric.annotation.Implements;
9 import org.robolectric.annotation.Resetter;
10 import org.robolectric.shadow.api.Shadow;
11 import org.robolectric.util.ReflectionHelpers.ClassParameter;
12 
13 import org.chromium.base.ResettersForTesting;
14 import org.chromium.base.task.PostTask;
15 import org.chromium.base.task.TaskTraits;
16 
17 /** Shadow implementation for {@link PostTask}. */
18 @Implements(PostTask.class)
19 public class ShadowPostTask {
20     @FunctionalInterface
21     public interface TestImpl {
postDelayedTask(@askTraits int taskTraits, Runnable task, long delay)22         void postDelayedTask(@TaskTraits int taskTraits, Runnable task, long delay);
23     }
24 
25     private static TestImpl sTestImpl;
26 
27     /** Set implementation for tests. */
setTestImpl(TestImpl testImpl)28     public static void setTestImpl(TestImpl testImpl) {
29         sTestImpl = testImpl;
30         ResettersForTesting.register(ShadowPostTask::reset);
31     }
32 
33     /** Resets the {@link TestImpl} instance, undoing any shadowing. */
34     @Resetter
reset()35     public static void reset() {
36         sTestImpl = null;
37     }
38 
39     @Implementation
postDelayedTask(@askTraits int taskTraits, Runnable task, long delay)40     public static void postDelayedTask(@TaskTraits int taskTraits, Runnable task, long delay) {
41         if (sTestImpl == null) {
42             // Can use reflection to call into the real method that is being shadowed. This is the
43             // same as not having a shadow.
44             Shadow.directlyOn(
45                     PostTask.class,
46                     "postDelayedTask",
47                     ClassParameter.from(int.class, taskTraits),
48                     ClassParameter.from(Runnable.class, task),
49                     ClassParameter.from(long.class, delay));
50         } else {
51             sTestImpl.postDelayedTask(taskTraits, task, delay);
52         }
53     }
54 }
55