1 /*
2  * Copyright (C) 2020 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.csuite.testing;
18 
19 import static com.google.common.truth.Truth.assertThat;
20 
21 /** An additional set of assertion methods useful for writing tests. */
22 // TODO(hzalek): Move this into a dedicated testing library.
23 public final class MoreAsserts {
24 
25     /**
26      * Facilitates the use of assertThrows from Java 8 by allowing method references to void methods
27      * that declare checked exceptions and is not meant to be directly implemented.
28      */
29     public interface ThrowingRunnable {
run()30         void run() throws Exception;
31     }
32 
33     /**
34      * Asserts that {@code runnable} throws an exception of type {@code expectedThrowable} when
35      * executed. If it does, the exception object is returned. Otherwise, if it does not throw an
36      * exception or does but of the unexpected type, an {@link AssertionError} is thrown.
37      *
38      * <p>This is mostly intended as a drop-in replacement of assertThrows that is only available in
39      * JUnit 4.13 and later.
40      *
41      * @param message the identifying message for the {@link AssertionError}
42      * @param expectedThrowable the expected type of the exception
43      * @param runnable a function that is expected to throw an exception when executed
44      * @return the exception thrown by {@code runnable}
45      */
assertThrows( Class<T> expectedClass, ThrowingRunnable runnable)46     public static <T extends Throwable> T assertThrows(
47             Class<T> expectedClass, ThrowingRunnable runnable) {
48         try {
49             runnable.run();
50         } catch (Throwable e) {
51             assertThat(e).isInstanceOf(expectedClass);
52             return expectedClass.cast(e);
53         }
54         throw new AssertionError(
55                 "Did not throw any when expected instance of: " + expectedClass.getName());
56     }
57 
MoreAsserts()58     private MoreAsserts() {}
59 }
60