• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2020 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.test;
6 
7 import androidx.test.InstrumentationRegistry;
8 
9 import org.junit.runners.model.FrameworkMethod;
10 import org.junit.runners.model.Statement;
11 
12 import java.util.concurrent.atomic.AtomicReference;
13 
14 /** junit {@link Statement} that runs a test method on the UI thread. */
15 /* package */ class UiThreadStatement extends Statement {
16     private final Statement mBase;
17 
UiThreadStatement(Statement base)18     public UiThreadStatement(Statement base) {
19         mBase = base;
20     }
21 
22     @Override
evaluate()23     public void evaluate() throws Throwable {
24         final AtomicReference<Throwable> exceptionRef = new AtomicReference<>();
25         InstrumentationRegistry.getInstrumentation()
26                 .runOnMainSync(
27                         () -> {
28                             try {
29                                 mBase.evaluate();
30                             } catch (Throwable throwable) {
31                                 exceptionRef.set(throwable);
32                             }
33                         });
34         Throwable throwable = exceptionRef.get();
35         if (throwable != null) throw throwable;
36     }
37 
38     /**
39      * @return True if the method is annotated with {@link UiThreadTest}.
40      */
shouldRunOnUiThread(FrameworkMethod method)41     public static boolean shouldRunOnUiThread(FrameworkMethod method) {
42         return method.getAnnotation(UiThreadTest.class) != null;
43     }
44 }
45