junit 测试ByteBuddy拦截器

6rqinv9w  于 2023-05-29  发布在  其他
关注(0)|答案(1)|浏览(155)

我正在使用ByteBuddy Agent创建一个Java Agent,如下所示:

public class Agent {

    private static final Logger logger = Logger.getLogger(Agent.class.getSimpleName());

    public static void premain(String agentArgs, Instrumentation inst) {

        logger.info("Entering premain method");

        // Put the name of the class to be instrumented here
        String targetClassName = "";

    
        new AgentBuilder.Default()
                .type(ElementMatchers.named(targetClassName))
                .transform(new DelegateTransformer(MethodInvocationInterceptor.class))
                .installOn(inst);

    }

变压器如下所示:

public class DelegateTransformer implements AgentBuilder.Transformer {

    private static Logger logger = Logger.getLogger(DelegateTransformer.class.getSimpleName());

    private final Class<?> delegateClass;

    DelegateTransformer(Class<?> delegateClass) {
        this.delegateClass = delegateClass;
    }
    
    @Override
    public DynamicType.Builder<?> transform(
            DynamicType.Builder<?> builder,
            TypeDescription typeDescription,
            ClassLoader classLoader,
            JavaModule module,
            ProtectionDomain protectionDomain) {
            
        return builder
                .method(ElementMatchers.any())
                .intercept(MethodDelegation.to(delegateClass));
    }
}

使用实际的拦截器:

public class MethodInvocationInterceptor {

    public static Logger LOGGER = Logger.getLogger(MethodInvocationInterceptor.class.getSimpleName());
    
    @RuntimeType
    public static Object intercept(@SuperMethod Method method, @SuperCall Callable<?> superCall, @AllArguments Object[] args) {
        

        // Do stuff here...

        try {
            return superCall.call();
        } catch (Exception e) {
            return null;
        }

    }
    
}

不,我想为每个元素编写测试,但实际上我在这里有点迷路了。我尝试了以下方法,但是由于不允许在已经加载的类中添加字段,所以失败了

@Test
    public void dispatchesMethodInvokationEvent() {
        ByteBuddyAgent.install();
        new ByteBuddy()
                .rebase(ExampleClass.class)
                .method(ElementMatchers.any())
                .intercept(MethodDelegation.to(MethodInvocationInterceptor.class))
                .make()
                .load(getClass().getClassLoader(), ClassReloadingStrategy.fromInstalledAgent());

        ExampleClass exampleClass = new ExampleClass();
        exampleClass.hello();

       // assertions
    }

关于我如何为上面提到的组件编写测试/示例,有什么提示吗?

ia2d9nvy

ia2d9nvy1#

如果你看看Byte Buddy GitHub中的测试,有很多例子。
通常,您可以将测试代理限制为给定的类加载器,然后仅为您的测试创建类加载器。
如果你的拦截器没有做它应该做的事情,你的测试应该失败。您还应该向代理添加一个侦听器以显示任何错误。

相关问题