Each time I run a test from my IDE I get the error
java.lang.IllegalStateException: Missing the '-javaagent' JVM argument.
If I create a run config and add the jvm arg everything is fine. However, the next time I run a test on the fly that is not a pre-configured run config I get the error again.
I thought maybe I could use @BeforeClass
to load the java agent dynamically. e.g.
@BeforeClass
public void loadAgent() {
String nameOfRunningVM = ManagementFactory.getRuntimeMXBean().getName();
String pid = nameOfRunningVM.substring(0, nameOfRunningVM.indexOf('@'));
VirtualMachine vm = VirtualMachine.attach(pid);
Class klass = JavaAgent.class;
CodeSource codeSource = klass.getProtectionDomain().getCodeSource();
String agentJar = codeSource.getLocation().getPath();
vm.loadAgent(agentJar, "");
vm.detach();
}
(maybe using a test listener might mean I don't copy and paste the code into every test class)
This works but it doesn't seem quite right.
Is there a way to do this without needing the pid?
Or is there a fundamentally better alternative to doing this?
For JDK8 the EA Agent Loader is a better choice and doesn't require the pid. However, it is discontinued for JDK9.
Kotlin example where my agent happens to be called JavaAgent!
AgentLoader.loadAgentClass(JavaAgent::class.java.name, "")