'How to get a class from which tests were run while byte buddy intercept the tests from super class?

I have a service class with a method which i'll intercept in runtime:

package service;

public class ServiceImpl {
    public void run() {
        // ...
    }
}

And test classes, using TestNG:

package tests.first;

import org.testng.annotations.Test;
import service.ServiceImpl;

public class A {
    @Test
    public void testA() {
        ServiceImpl service = new ServiceImpl();
        // ...
        service.run();
        // ...
    }
}

Another class that extends the A class in different package:

package tests.second;

import org.testng.annotations.Test;
import service.ServiceImpl;

public class B extends A {
    @Test
    public void testB() {
        ServiceImpl service = new ServiceImpl();
        // ...
        service.run();
        // ...
    }
}

Also I have a proxy agent that used as an interceptor for ServiceImpl.run method (using byte buddy library).

that what i tried in the inteceptor:

    public void intercept() {
        Arrays.asList(Thread.currentThread().getStackTrace())
            .stream()
            .map(e -> e.getClassName() + "." + e.getMethodName())
        // some actions
    }

Question: I'm running tests in class B and while the tests are running, the interceptor should get the class name and method name from the stack trace (or something else). But tests start with class A and return className: tests.first; methodName: testA, is it possible to get in that time className for class B which the tests were run?



Solution 1:[1]

I assume that you Instrument both classes A and B. In this case you will see the respective stack trace of these classes when they are executed as test. Byte Buddy does not interfer with stack traces or test mechanics.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rafael Winterhalter