I'm trying to test a private method which takes the below parameters as input:
ClassToBeTested
delete(
someId1: String,
aList: List<CustomObject>,
someId2: String,
someId3: String,
someId4: String
) : Long? {
}
TestClass
val method = ClassToBeTested.javaClass.getDeclaredMethod("delete", String::class.java,
List::class.java, String::class.java, String::class.java, String::class.java)
method.isAccessible = true
val testId = method.invoke(ClassToBeTested, someId1, aList, someId2, someId3, someId4)
I end up getting the below error:
java.lang.NoSuchMethodException:
ClassToBeTested$Companion.delete(java.lang.String, java.util.Arrays$ArrayList, java.lang.String, java.lang.String, java.lang.String)
When I tried changing the above method declaration as:
val method = ClassToBeTested.javaClass.getDeclaredMethod("delete", String::class.java,
List<CustomObject>::class.java, String::class.java, String::class.java, String::class.java)
I get the below error:
Kotlin: Only classes are allowed on the left hand side of a class literal
Is there anyway we can test the private function which takes a parameter of List of Custom Objects?
You can use Kotlin's declaredMemberFunctions property to find it based on its name alone:
data class CustomObject(val id: String)
class ClassToBeTested {
private fun delete(
someId1: String,
aList: List<CustomObject>,
someId2: String,
someId3: String,
someId4: String
): Long? {
return someId1.toLongOrNull()
}
}
class SampleTest {
@Test
fun test1() {
val instance = ClassToBeTested()
val method = instance::class.declaredMemberFunctions.first { it.name == "delete" }.apply { isAccessible = true }
val result = method.call(instance, "1", emptyList<CustomObject>(), "2", "3", "4")
assertEquals(1L, result)
}
}
Don't use reflection for this. Simply make the method internal
and call it directly from your tests. You can even add an annotation like @VisibleForTesting
or @TestOnly
, those are available in various libraries.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.