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 android.util.Log; 19 20 import com.google.common.collect.ImmutableSet; 21 import com.google.errorprone.annotations.FormatMethod; 22 import com.google.errorprone.annotations.FormatString; 23 24 import java.util.Objects; 25 26 /** Base implementation for static mockers. */ 27 public abstract class AbstractStaticMocker { 28 29 static final String TAG = "StaticMocker"; 30 31 protected final String mTag = getClass().getSimpleName(); 32 33 private final StaticClassChecker mStaticClassChecker; 34 AbstractStaticMocker(StaticClassChecker staticClassChecker)35 protected AbstractStaticMocker(StaticClassChecker staticClassChecker) { 36 mStaticClassChecker = Objects.requireNonNull(staticClassChecker); 37 } 38 39 @FormatMethod logV(@ormatString String fmt, Object... args)40 protected final void logV(@FormatString String fmt, Object... args) { 41 Log.v( 42 TAG, 43 "on " 44 + mStaticClassChecker.getTestName() 45 + " by " 46 + mTag 47 + ": " 48 + String.format(fmt, args)); 49 } 50 assertSpiedOrMocked(Class<?> clazz)51 protected final void assertSpiedOrMocked(Class<?> clazz) { 52 if (!mStaticClassChecker.isSpiedOrMocked(clazz)) { 53 throw new ClassNotSpiedOrMockedException( 54 clazz, mStaticClassChecker.getSpiedOrMockedClasses()); 55 } 56 } 57 58 @SuppressWarnings("OverrideThrowableToString") // to remove AbstractStaticMocker.$ from name 59 public static final class ClassNotSpiedOrMockedException extends IllegalStateException { 60 private final Class<?> mMissingClass; 61 private final ImmutableSet<Class<?>> mSpiedOrMockedClasses; 62 ClassNotSpiedOrMockedException( Class<?> missingClass, ImmutableSet<Class<?>> spiedOrMockedClasses)63 private ClassNotSpiedOrMockedException( 64 Class<?> missingClass, ImmutableSet<Class<?>> spiedOrMockedClasses) { 65 super( 66 "Test doesn't static spy or mock " 67 + missingClass 68 + ", only: " 69 + spiedOrMockedClasses); 70 mMissingClass = missingClass; 71 mSpiedOrMockedClasses = spiedOrMockedClasses; 72 } 73 getMissingClass()74 public Class<?> getMissingClass() { 75 return mMissingClass; 76 } 77 getSpiedOrMockedClasses()78 public ImmutableSet<Class<?>> getSpiedOrMockedClasses() { 79 return mSpiedOrMockedClasses; 80 } 81 82 @Override toString()83 public String toString() { 84 return getClass().getSimpleName() + ": " + getMessage(); 85 } 86 } 87 } 88