byte-buddy icon indicating copy to clipboard operation
byte-buddy copied to clipboard

Can not redefine a class when running tests with coverage

Open luozhenyu opened this issue 3 years ago • 1 comments

Reproduce

I use the jacoco plugin to generate a code coverage report. However, it throws a UnsupportedOperationException with a message 'class redefinition failed: attempted to delete a method'.

The jacoco plugin adds a method named '$jacocoInit()' to each class, but it seems byte-buddy ignores this generated method.

My Code

import net.bytebuddy.ByteBuddy;
import net.bytebuddy.agent.ByteBuddyAgent;
import net.bytebuddy.dynamic.loading.ClassReloadingStrategy;
import org.junit.jupiter.api.Test;

class Main {

    @Test
    void testJacoco() throws Exception {
        ByteBuddyAgent.install();

        new ByteBuddy()
                .redefine(Main.class)
                .make()
                .load(AuthRequest.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent());
    }

}

luozhenyu avatar May 09 '22 12:05 luozhenyu

Yes, you are getting the class file from disk in this case. redefine can accept a ClassFileLocator as a second argument. You would need to get hold of the extracted class file here.

This might be easier to achieve with AgentBuilder which can also redefine methods and automatically picks up class files from previous transformers when retransformation is enabled.

raphw avatar May 09 '22 21:05 raphw

AgentBuilder

it's there example to fix this error, use ClassFileLocator or AgentBuilder

leaderli avatar Oct 27 '22 17:10 leaderli