Can not redefine a class when running tests with coverage
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());
}
}
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.
AgentBuilder
it's there example to fix this error, use ClassFileLocator or AgentBuilder