|
| 1 | +package com.baeldung.privateFunction |
| 2 | + |
| 3 | +import org.junit.jupiter.api.Assertions.assertEquals |
| 4 | +import org.junit.jupiter.api.Test |
| 5 | + |
| 6 | +class PrivateFunctionUnitTest { |
| 7 | + |
| 8 | + @Test |
| 9 | + fun `Makes call to private method Using Reflection`() { |
| 10 | + val obj = MyClass() |
| 11 | + val privateMethod = MyClass::class.java.getDeclaredMethod("privateMethod") |
| 12 | + privateMethod.isAccessible = true |
| 13 | + |
| 14 | + val output = privateMethod.invoke(obj) |
| 15 | + |
| 16 | + assertEquals("This is a private method", output) |
| 17 | + } |
| 18 | + |
| 19 | + @Test |
| 20 | + fun `Makes call to private method Using Inner Class`() { |
| 21 | + val obj = MyClassWithInnerClass() |
| 22 | + val innerObj = obj.MyInnerClass() |
| 23 | + val output = innerObj.callPrivateMethod() |
| 24 | + |
| 25 | + assertEquals("This is a private method", output) |
| 26 | + } |
| 27 | + |
| 28 | + @Test |
| 29 | + fun `Makes call to private method Using public method`() { |
| 30 | + val obj = MyPublicClass() |
| 31 | + |
| 32 | + assertEquals("This is a private method", obj.callPrivateMethod()) |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +class MyClass { |
| 37 | + private fun privateMethod(): String { |
| 38 | + return "This is a private method" |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +class MyClassWithInnerClass { |
| 43 | + private fun privateMethod(): String { |
| 44 | + return "This is a private method" |
| 45 | + } |
| 46 | + |
| 47 | + inner class MyInnerClass { |
| 48 | + fun callPrivateMethod(): String { |
| 49 | + return privateMethod() |
| 50 | + } |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +class MyPublicClass { |
| 55 | + private fun privateMethod(): String { |
| 56 | + return "This is a private method" |
| 57 | + } |
| 58 | + |
| 59 | + fun callPrivateMethod(): String { |
| 60 | + return privateMethod() |
| 61 | + } |
| 62 | +} |
0 commit comments