Debian Codegraph @

libartservice/service/javatests/com/android/server/art/testing/StaticMockitoRule.java

raw
1 /*
2 * Copyright (C) 2022 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.server.art.testing;
18
19 import static com.android.dx.mockito.inline.extended.ExtendedMockito.mockitoSession;
20
21 import com.android.dx.mockito.inline.extended.StaticMockitoSession;
22 import com.android.dx.mockito.inline.extended.StaticMockitoSessionBuilder;
23
24 import org.junit.rules.MethodRule;
25 import org.junit.runners.model.FrameworkMethod;
26 import org.junit.runners.model.Statement;
27 import org.mockito.junit.MockitoRule;
28 import org.mockito.quality.Strictness;
29
30 /**
31 * Similar to {@link MockitoRule}, but uses {@StaticMockitoSession}, which allows mocking static
32 * methods.
33 */
34 public class StaticMockitoRule implements MethodRule {
35 private Class<?>[] mClasses;
36
37 public StaticMockitoRule(Class<?>... classes) {
38 mClasses = classes;
39 }
40
41 @Override
42 public Statement apply(Statement base, FrameworkMethod method, Object target) {
43 return new Statement() {
44 public void evaluate() throws Throwable {
45 StaticMockitoSessionBuilder builder =
46 mockitoSession()
47 .name(target.getClass().getSimpleName() + "." + method.getName())
48 .initMocks(target)
49 .strictness(Strictness.STRICT_STUBS);
50
51 for (Class<?> clazz : mClasses) {
52 builder.mockStatic(clazz);
53 }
54
55 StaticMockitoSession session = builder.startMocking();
56 Throwable testFailure = evaluateSafely(base);
57 session.finishMocking(testFailure);
58 if (testFailure != null) {
59 throw testFailure;
60 }
61 }
62
63 private Throwable evaluateSafely(Statement base) {
64 try {
65 base.evaluate();
66 return null;
67 } catch (Throwable throwable) {
68 return throwable;
69 }
70 }
71 };
72 }
73 }