• 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 com.google.errorprone.annotations.CanIgnoreReturnValue
19 import org.junit.AssumptionViolatedException
20 
21 /**
22  * Test utilities related to assertions
23  */
24 object Assert {
25     /**
26      * Assert that a particular exception type is thrown.
27      */
28     @JvmStatic
29     @CanIgnoreReturnValue
assertThrowsnull30     fun <E : Throwable?> assertThrows(message: String? = null,
31         exception: Class<E>? = null,
32         executable: () -> Unit): E {
33         val exceptionType = exception?.toString() ?: "an exception"
34         try {
35             executable()
36             throw AssertionError(message ?: "Expected to throw $exceptionType but nothing thrown")
37         } catch (e: Throwable) {
38             if (exception?.isInstance(e) == true) {
39                 return e as E
40             }
41             throw e
42         }
43     }
44 
45     @JvmStatic
46     @CanIgnoreReturnValue
assertThrowsnull47     fun assertThrows(message: String? = null, executable: () -> Unit): Exception =
48         assertThrows(message, Exception::class.java, executable)
49 
50     // This method is just needed to maintain compatibility with existing Java callers - it should
51     // be removed once possible
52     @JvmStatic
53     @CanIgnoreReturnValue
54     fun <E : Throwable?> assertThrows(exception: Class<E>? = null, executable: Runnable): E =
55         assertThrows(null, exception) { executable.run() }
56 
57     /**
58      * Assert that a exception is not thrown.
59      */
60     @JvmStatic
61     @JvmOverloads
assertDoesNotThrownull62     fun assertDoesNotThrow(message: String? = null, executable: () -> Unit) {
63         try {
64             executable()
65         } catch (e: Exception) {
66             if (message != null) {
67                 throw AssumptionViolatedException(message, e)
68             }
69             throw e
70         }
71     }
72 }
73