Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit Test framework for Javaagent Instrumentation Framework

What are the standard ways for creating unit tests for code of a Java agent and instrumentation libraries. I have created a Java agent using the Byte Buddy framework for developing a profiler on top of a web applictaion and now i wanted to write JUnit test cases for this agent.

like image 672
Vimlesh Yadav Avatar asked Oct 22 '25 16:10

Vimlesh Yadav


1 Answers

You can take inspiration from Byte Buddy's own unit tests for creating a Java agent. For this, declare a test dependency on the byte-buddy-agent module. That module includes a class that is capable of attaching a Java agent at runtime using ByteBuddyAgent.install() which returns an Instrumentation instance. Make sure that you remove a Java agent after running a unit test. Otherwise, your agent will remain active for any subsequent test.

On tricky part for creating repeatable tests is the fact that a class must not be loaded before the agent is applied. Byte Buddy's test harness solves this by creating a ByteArrayClassLoader that is capable of all the classes that are subject to instrumentation. As this class loader is created dynamically, this can be guaranteed.

Most JDK-bundled VMs are capable of a runtime attachment of a Java agent. To be sure, Byte Buddy does however define a AgentAttachmentRule for JUnit that asserts this capability before running a test. You might consider this as well.

like image 165
Rafael Winterhalter Avatar answered Oct 25 '25 05:10

Rafael Winterhalter