1 /* 2 * Copyright (C) 2016 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 17 package com.android.documentsui.testing; 18 19 import static org.junit.Assert.assertEquals; 20 import static org.junit.Assert.assertTrue; 21 22 import java.util.concurrent.CompletableFuture; 23 import java.util.concurrent.ExecutionException; 24 import java.util.concurrent.TimeUnit; 25 import java.util.concurrent.TimeoutException; 26 import java.util.function.Predicate; 27 28 import javax.annotation.Nullable; 29 30 /** 31 * Test {@link Predicate} that can be used to spy on, control responses from, 32 * and make assertions against values tested. 33 */ 34 public class TestPredicate<T> implements Predicate<T> { 35 36 private final CompletableFuture<T> mFuture = new CompletableFuture<>(); 37 private @Nullable T mLastValue; 38 private boolean mNextReturnValue; 39 private boolean mCalled; 40 41 @Override test(T t)42 public boolean test(T t) { 43 mCalled = true; 44 mLastValue = t; 45 mFuture.complete(t); 46 return mNextReturnValue; 47 } 48 assertLastArgument(@ullable T expected)49 public void assertLastArgument(@Nullable T expected) { 50 assertEquals(expected, mLastValue); 51 } 52 assertCalled()53 public void assertCalled() { 54 assertTrue(mCalled); 55 } 56 nextReturn(boolean value)57 public void nextReturn(boolean value) { 58 mNextReturnValue = value; 59 } 60 waitForCall(int timeout, TimeUnit unit)61 public @Nullable T waitForCall(int timeout, TimeUnit unit) 62 throws InterruptedException, ExecutionException, TimeoutException { 63 return mFuture.get(timeout, unit); 64 } 65 } 66