问题
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:
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.
来源:https://stackoverflow.com/questions/35577485/junit-test-framework-for-javaagent-instrumentation-framework