1 /*
2  * Copyright (C) 2024 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 package com.android.adservices.mockito;
17 
18 import static org.mockito.ArgumentMatchers.any;
19 import static org.mockito.ArgumentMatchers.anyBoolean;
20 import static org.mockito.ArgumentMatchers.anyInt;
21 import static org.mockito.Mockito.doAnswer;
22 import static org.mockito.Mockito.mock;
23 import static org.mockito.Mockito.when;
24 
25 import android.content.Context;
26 
27 import com.android.adservices.shared.common.ApplicationContextSingleton;
28 import com.android.adservices.shared.spe.logging.JobServiceLogger;
29 import com.android.adservices.shared.testing.JobServiceLoggingCallback;
30 
31 /** Implements {@link SharedMocker} using {@code Mockito}. */
32 public final class SharedMockitoMocker extends AbstractMocker implements SharedMocker {
33 
34     @Override
setApplicationContextSingleton()35     public Context setApplicationContextSingleton() {
36         Context context = mock(Context.class);
37         logV("setApplicationContextSingleton(): will use %s as appContext", context);
38 
39         when(context.getApplicationContext()).thenReturn(context);
40         ApplicationContextSingleton.setForTests(context);
41 
42         return context;
43     }
44 
45     @Override
syncRecordOnStopJob(JobServiceLogger logger)46     public JobServiceLoggingCallback syncRecordOnStopJob(JobServiceLogger logger) {
47         JobServiceLoggingCallback callback = new JobServiceLoggingCallback();
48 
49         doAnswer(
50                         invocation -> {
51                             logV("calling callback %s on %s", callback, invocation);
52                             callback.onLoggingMethodCalled();
53                             return null;
54                         })
55                 .when(logger)
56                 .recordOnStopJob(any(), anyInt(), anyBoolean());
57 
58         return callback;
59     }
60 }
61