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