|
| 1 | +package com.baeldung.java.reflection; |
| 2 | + |
| 3 | +import java.lang.reflect.InvocationTargetException; |
| 4 | +import java.lang.reflect.Method; |
| 5 | +import org.testng.Assert; |
| 6 | +import org.testng.annotations.Test; |
| 7 | + |
| 8 | +public class OperationsUnitTest { |
| 9 | + |
| 10 | + public OperationsUnitTest() { |
| 11 | + } |
| 12 | + |
| 13 | + @Test(expectedExceptions = IllegalAccessException.class) |
| 14 | + public void givenObject_whenInvokePrivatedMethod_thenFail() throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{ |
| 15 | + Method andInstanceMethod = Operations.class.getDeclaredMethod("and", boolean.class, boolean.class); |
| 16 | + |
| 17 | + Operations operationsInstance = new Operations(); |
| 18 | + Boolean result = (Boolean)andInstanceMethod.invoke(operationsInstance, true, false); |
| 19 | + |
| 20 | + Assert.assertFalse(result); |
| 21 | + } |
| 22 | + |
| 23 | + @Test |
| 24 | + public void givenObject_whenInvokePrivateMethod_thenCorrect() throws Exception { |
| 25 | + Method andInstanceMethod = Operations.class.getDeclaredMethod("and", boolean.class, boolean.class); |
| 26 | + andInstanceMethod.setAccessible(true); |
| 27 | + |
| 28 | + Operations operationsInstance = new Operations(); |
| 29 | + Boolean result = (Boolean)andInstanceMethod.invoke(operationsInstance, true, false); |
| 30 | + |
| 31 | + Assert.assertFalse(result); |
| 32 | + } |
| 33 | + |
| 34 | + @Test |
| 35 | + public void givenObject_whenInvokePublicMethod_thenCorrect() throws Exception { |
| 36 | + Method sumInstanceMethod = Operations.class.getMethod("sum", int.class, double.class); |
| 37 | + |
| 38 | + Operations operationsInstance = new Operations(); |
| 39 | + Double result = (Double)sumInstanceMethod.invoke(operationsInstance, 1, 3); |
| 40 | + |
| 41 | + Assert.assertTrue(4 == result); |
| 42 | + } |
| 43 | + |
| 44 | + @Test |
| 45 | + public void givenObject_whenInvokeStaticMethod_thenCorrect() throws Exception { |
| 46 | + Method multiplyStaticMethod = Operations.class.getDeclaredMethod("multiply",float.class, long.class); |
| 47 | + |
| 48 | + Double result = (Double)multiplyStaticMethod.invoke(null, 3.5f, 2); |
| 49 | + |
| 50 | + Assert.assertTrue(7 == result); |
| 51 | + } |
| 52 | + |
| 53 | +} |
0 commit comments