1 /*
2  * Copyright 2023 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 androidx.camera.testing.impl.mocks.helpers;
18 
19 import org.jspecify.annotations.NonNull;
20 import org.jspecify.annotations.Nullable;
21 
22 import java.util.ArrayList;
23 import java.util.List;
24 
25 /**
26  * Utility for capturing arguments, usually in fake class method invocations for testing.
27  *
28  * @param <T> the type of the arguments to capture
29  */
30 public class ArgumentCaptor<T> {
31     private final List<T> mArguments = new ArrayList<>();
32     private ArgumentMatcher<T> mArgumentMatcher;
33 
34     /**
35      * Creates a new instance of {@link ArgumentCaptor}.
36      */
ArgumentCaptor()37     public ArgumentCaptor() {}
38 
39     /**
40      * Creates a new instance of {@link ArgumentCaptor} with the given parameter.
41      *
42      * @param argumentMatcher specifies the matching criteria for capturing
43      */
ArgumentCaptor(@onNull ArgumentMatcher<T> argumentMatcher)44     public ArgumentCaptor(@NonNull ArgumentMatcher<T> argumentMatcher) {
45         mArgumentMatcher = argumentMatcher;
46     }
47 
48     /**
49      * Returns the last value captured, or {@code null} if no value has been captured yet.
50      */
getValue()51     public @Nullable T getValue() {
52         if (mArguments.size() == 0) {
53             return null;
54         }
55 
56         return mArguments.get(mArguments.size() - 1);
57     }
58 
59     /**
60      * Returns a list that contains all values captured, or an empty list if no value has been
61      * captured yet.
62      */
getAllValues()63     public @NonNull List<T> getAllValues() {
64         return mArguments;
65     }
66 
67     /**
68      * Adds arguments to capture list according to argument matching rule (if exists).
69      *
70      * @param argumentList the list of arguments to capture
71      */
setArguments(@onNull List<T> argumentList)72     public void setArguments(@NonNull List<T> argumentList) {
73         for (T argument : argumentList) {
74             if (mArgumentMatcher == null || mArgumentMatcher.matches(argument)) {
75                 mArguments.add(argument);
76             }
77         }
78     }
79 }
80