• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2023 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.bedstead.nene.utils
17 
18 import org.junit.AssumptionViolatedException
19 
20 /**
21  * Test utilities related to assertions
22  */
23 object Assert {
24     /**
25      * Assert that a particular exception type is thrown.
26      */
27     @JvmStatic
assertThrowsnull28     fun <E : Throwable?> assertThrows(message: String? = null,
29         exception: Class<E>? = null,
30         executable: () -> Unit): E {
31         val exceptionType = exception?.toString() ?: "an exception"
32         try {
33             executable()
34             throw AssertionError(message ?: "Expected to throw $exceptionType but nothing thrown")
35         } catch (e: Throwable) {
36             if (exception?.isInstance(e) == true) {
37                 return e as E
38             }
39             throw e
40         }
41     }
42 
43     @JvmStatic
assertThrowsnull44     fun assertThrows(message: String? = null, executable: () -> Unit): Exception =
45         assertThrows(message, Exception::class.java, executable)
46 
47     // This method is just needed to maintain compatibility with existing Java callers - it should
48     // be removed once possible
49     @JvmStatic
50     fun <E : Throwable?> assertThrows(exception: Class<E>? = null, executable: Runnable): E =
51         assertThrows(null, exception) { executable.run() }
52 
53     /**
54      * Assert that a exception is not thrown.
55      */
56     @JvmStatic
57     @JvmOverloads
assertDoesNotThrownull58     fun assertDoesNotThrow(message: String? = null, executable: () -> Unit) {
59         try {
60             executable()
61         } catch (e: Exception) {
62             if (message != null) {
63                 throw AssumptionViolatedException(message, e)
64             }
65             throw e
66         }
67     }
68 }
69