• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 package com.android.server.testutils;
17 
18 import android.test.MoreAsserts;
19 
20 import junit.framework.Assert;
21 
22 import org.mockito.Mockito;
23 import org.mockito.stubbing.Answer;
24 
25 public class TestUtils {
TestUtils()26     private TestUtils() {
27     }
28 
29     public interface ExceptionRunnable {
run()30         void run() throws Exception;
31     }
32 
assertExpectException(Class<? extends Throwable> expectedExceptionType, String expectedExceptionMessageRegex, ExceptionRunnable r)33     public static void assertExpectException(Class<? extends Throwable> expectedExceptionType,
34             String expectedExceptionMessageRegex, ExceptionRunnable r) {
35         try {
36             r.run();
37         } catch (Throwable e) {
38             Assert.assertTrue(
39                     "Expected exception type was " + expectedExceptionType.getName()
40                     + " but caught " + e.getClass().getName(),
41                     expectedExceptionType.isAssignableFrom(e.getClass()));
42             if (expectedExceptionMessageRegex != null) {
43                 MoreAsserts.assertContainsRegex(expectedExceptionMessageRegex, e.getMessage());
44             }
45             return; // Pass.
46         }
47         Assert.fail("Expected exception type " + expectedExceptionType.getName()
48                 + " was not thrown");
49     }
50 
51     /**
52      * EasyMock-style "strict" mock that throws immediately on any interaction that was not
53      * explicitly allowed.
54      *
55      * You can allow certain method calls on a whitelist basis by stubbing them e.g. with
56      * {@link Mockito#doAnswer}, {@link Mockito#doNothing}, etc.
57      */
strictMock(Class<T> c)58     public static <T> T strictMock(Class<T> c) {
59         return Mockito.mock(c, (Answer) invocation -> {
60             throw new AssertionError("Unexpected invocation: " + invocation);
61         });
62     }
63 }
64