blob: 1be298d2c8c5523c5529fec850507d3c73253437 [file] [log] [blame]
Bernardo Rufino41349c02018-01-10 21:09:28 +00001/*
2 * Copyright (C) 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
17package com.android.server.backup.testing;
18
19import com.android.internal.util.FunctionalUtils.ThrowingRunnable;
20
21import java.util.concurrent.Callable;
22
23public class TestUtils {
24 /**
25 * Calls {@link Runnable#run()} and returns if no exception is thrown. Otherwise, if the
26 * exception is unchecked, rethrow it; if it's checked wrap in a {@link RuntimeException} and
27 * throw.
28 *
29 * <p><b>Warning:</b>DON'T use this outside tests. A wrapped checked exception is just a failure
30 * in a test.
31 */
32 public static void uncheck(ThrowingRunnable runnable) {
33 try {
34 runnable.runOrThrow();
35 } catch (Exception e) {
36 throw wrapIfChecked(e);
37 }
38 }
39
40 /**
41 * Calls {@link Callable#call()} and returns the value if no exception is thrown. Otherwise, if
42 * the exception is unchecked, rethrow it; if it's checked wrap in a {@link RuntimeException}
43 * and throw.
44 *
45 * <p><b>Warning:</b>DON'T use this outside tests. A wrapped checked exception is just a failure
46 * in a test.
47 */
48 public static <T> T uncheck(Callable<T> callable) {
49 try {
50 return callable.call();
51 } catch (Exception e) {
52 throw wrapIfChecked(e);
53 }
54 }
55
56 /**
57 * Wrap {@code e} in a {@link RuntimeException} only if it's not one already, in which case it's
58 * returned.
59 */
60 public static RuntimeException wrapIfChecked(Exception e) {
61 if (e instanceof RuntimeException) {
62 return (RuntimeException) e;
63 }
64 return new RuntimeException(e);
65 }
66
67 private TestUtils() {}
68}