1 /*
2  * Copyright 2018 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 androidx.testutils
18 
19 import com.google.common.truth.ExpectFailure
20 import com.google.common.truth.ThrowableSubject
21 import com.google.common.truth.Truth.assertThat
22 import com.google.common.truth.TruthFailureSubject
23 
assertThrowsnull24 inline fun <reified T : Throwable> assertThrows(body: () -> Unit): ThrowableSubject {
25     try {
26         body()
27     } catch (e: Throwable) {
28         if (e is T) {
29             return assertThat(e)
30         }
31         throw e
32     }
33     throw AssertionError("Body completed successfully. Expected ${T::class.java.simpleName}.")
34 }
35 
assertThrowsnull36 inline fun assertThrows(body: () -> Unit): TruthFailureSubject {
37     try {
38         body()
39     } catch (e: Throwable) {
40         if (e is AssertionError) {
41             return ExpectFailure.assertThat(e)
42         }
43         throw e
44     }
45     throw AssertionError("Body completed successfully. Expected AssertionError")
46 }
47 
failnull48 fun fail(message: String? = null): Nothing = throw AssertionError(message)
49 
50 // The assertThrows above cannot be used from Java.
51 @Suppress("UNCHECKED_CAST")
52 fun <T : Throwable?> assertThrows(expectedType: Class<T>, runnable: Runnable): ThrowableSubject {
53     try {
54         runnable.run()
55     } catch (t: Throwable) {
56         if (expectedType.isInstance(t)) {
57             return assertThat(t)
58         }
59         throw t
60     }
61     throw AssertionError("Body completed successfully. Expected ${expectedType.simpleName}")
62 }
63