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.
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.

- 42,759
- 13
- 108
- 192
-
1Can you please speficy how to remove the agent in a test? I don't see a #uninstall or similar. Does the "trick" of using a ByteArrayClassLoader also work when loading classes from within the JDK? I am getting a "java.lang.SecurityException: Prohibited package name: java.io". – geld0r May 22 '16 at 19:38
-
2Install returns a transformer that can be removed via the instrumentation interface. – Rafael Winterhalter May 22 '16 at 21:34
-
Are bytebuddy's test-jars available in any maven repository to allow us reuse the tools you suggest like "AgentAttachmentRule" ? – user1767316 Jan 01 '17 at 16:11
-
No they are not, but its 10 lines of code which should be easy enough to recreate. (I do not want to apply such small testing tools with a stable API.) – Rafael Winterhalter Jan 01 '17 at 16:23