kotlinaopaspectjaspectj-maven-plugin

Get class name, where method is implemented, with AspectJ


I have a class with methods that has annotation (io.qase.api.annotation.Step)

Class myStepsClass() {

@Step
fun stepOne() {***}

@Step
fun stepTwo() {***}
}

I would like to print "step" method name during the execution, and show a Class name where step method is implemented: in this example this is myStepsClass.

I created Aspect file

@Aspect
class Aspects {

    @Before("@annotation(io.qase.api.annotation.Step)")
    fun stepMethod(joinPoint: JoinPoint) {
        println("Step called: ${getMethodName(joinPoint)}")
    }

    private fun getMethodName(joinPoint: JoinPoint): String {
        val methodSignature = joinPoint.signature as MethodSignature
        return methodSignature.name
    }
}

It prints Step called: stepOne when I call step "stepOne" method in other methods (like Test methods). How to get the parent class name - myStepsClass?

To print something like

Step Called: myStepsClass -> stepOne

Step Called: myStepsClass -> stepTwo

I have created a project with code: https://github.com/heavy-razzer/AssertJ-Maven-Kotlin


Solution

  • (joinPoint.signature as MethodSignature).declaringTypeName will do the trick. It will return the full path to the method, split by "." symbol.

    So you can have

    private fun getParentClassName(joinPoint: JoinPoint): String {
      return (joinPoint.signature as MethodSignature).declaringTypeName.split(".").last()
    }
    

    to get name of class, where this method is decribed.

    I have updated my GH repo with the example.

    Output will be:

    Test started: Very simple test
    Steps->printCaption(): []
    Step: This this a simple test
    Test step performed: printCaption
    Steps->printMessage(): []
    Step: Testing in progress 
    Test step performed: printMessage