1 // Copyright 2023 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.util; 6 7 import org.chromium.base.ThreadUtils; 8 9 import java.util.concurrent.ExecutionException; 10 import java.util.concurrent.FutureTask; 11 12 /** Helper methods to deal with threading related tasks in tests. */ 13 public class TestThreadUtils { 14 /** 15 * Since PostTask goes through c++, and order is not guaranteed between c++ and Java Handler 16 * tasks, in many cases it's not sufficient to PostTask to the UI thread to check if UI 17 * properties like visibility are updated in response to a click, as UI updates go through a 18 * Java Handler and may run after the posted PostTask task. 19 * 20 * You should strongly prefer to wait on the signal you care about (eg. use Espresso to wait for 21 * a view to be displayed) instead of flushing tasks. 22 */ flushNonDelayedLooperTasks()23 public static void flushNonDelayedLooperTasks() { 24 if (ThreadUtils.runningOnUiThread()) return; 25 var task = new FutureTask<Void>(() -> {}, null); 26 ThreadUtils.getUiThreadHandler().post(task); 27 try { 28 task.get(); 29 } catch (InterruptedException | ExecutionException e) { 30 } 31 } 32 } 33