mardi 12 juillet 2022

How to set annotations on a method using reflection?

I'm trying to unit test an aspect.

    val joinPoint = mock<ProceedingJoinPoint>()
    val methodSignature = mock<MethodSignature>()

    val roleArray = arrayOf("someTestRole")
    val annotation = AccessCheck::class.constructors.first().call(roleArray)
    val method = this.javaClass.getMethod("myMethod")
    method.setAccessible(true)
a)  method.annotations = roleArray
b)  method.annotations[0] = annotation

Cannot invoke b) because method.annotations returns null.
Cannot invoke a) because method.annotations is val.
Cannot make Method a mock, since it's a final class.

Is there any way to surpass that?

This is what annotation class looks like:

@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FUNCTION)
annotation class AccessCheck(val userRoles: Array<String>)




Aucun commentaire:

Enregistrer un commentaire