1 /*
 2  * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved.
 3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 4  *
 5  * This code is free software; you can redistribute it and/or modify it
 6  * under the terms of the GNU General Public License version 2 only, as
 7  * published by the Free Software Foundation.
 8  *
 9  * This code is distributed in the hope that it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12  * version 2 for more details (a copy is included in the LICENSE file that
13  * accompanied this code).
14  *
15  * You should have received a copy of the GNU General Public License version
16  * 2 along with this work; if not, write to the Free Software Foundation,
17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18  *
19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20  * or visit www.oracle.com if you need additional information or have any
21  * questions.
22  */
23 
24 import java.lang.invoke.MethodHandles;
25 import java.lang.reflect.Method;
26 import java.lang.reflect.code.interpreter.Interpreter;
27 import java.lang.runtime.CodeReflection;
28 
29 import org.testng.Assert;
30 import org.testng.annotations.DataProvider;
31 import org.testng.annotations.Test;
32 
33 /*
34  * @test
35  * @run testng TestThrowing
36  */
37 
38 public class TestThrowing {
39 
40     @Test(dataProvider = "methods-exceptions")
41     public void testThrowsCorrectException(String methodName, Class<? extends Throwable> expectedExceptionType) throws NoSuchMethodException {
42         Method method = TestThrowing.class.getDeclaredMethod(methodName);
43         Assert.assertThrows(expectedExceptionType, () -> Interpreter.invoke(MethodHandles.lookup(), method.getCodeModel().orElseThrow()));
44     }
45 
46     @DataProvider(name = "methods-exceptions")
47     static Object[][] testData() throws NoSuchMethodException {
48         return new Object[][]{
49                 {"throwsError", TestError.class},
50                 {"throwsRuntimeException", TestRuntimeException.class},
51                 {"throwsCheckedException", TestCheckedException.class},
52         };
53     }
54 
55     public static class TestError extends Error {
56 
57     }
58 
59     public static class TestRuntimeException extends RuntimeException {
60 
61     }
62 
63     public static class TestCheckedException extends Exception {
64 
65     }
66 
67     @CodeReflection
68     static void throwsError() {
69         throw new TestError();
70     }
71 
72     @CodeReflection
73     static void throwsRuntimeException() {
74         throw new TestRuntimeException();
75     }
76 
77     @CodeReflection
78     static void throwsCheckedException() throws TestCheckedException {
79         throw new TestCheckedException();
80     }
81 }