title: Junit- How to attach test to an existing process
body: <p>I have maven project, and running running <code>mvn test</code> executes test cases within a separate process. </p>
  
  <p>My ask is: Is there any way to run tests by attaching to an existing process?
  So that tests can use the attached process environment.</p>
  
  <p>I found surefire has <code>JVM</code>property, <a href="http://maven.apache.org/surefire/maven-surefire-plugin/test-mojo.html#jvm" rel="nofollow">found here</a>, but could not get how to set it, if this is correct understanding.</p>
  
  <p><strong>Update:</strong>
  As the project is SpringBoot based, so i executed server (Say it test server) like this-</p>
  
  <pre><code>java -jar target/server-0.0.1-SNAPSHOT.jar
  </code></pre>
  
  <p>And updated Junit test classes like this-</p>
  
  <pre><code>@Before
  public void setup() throws Exception {
      VirtualMachine virtualMachine = attach(getTestServerVM());
      System.out.println(virtualMachine.id());
  }
  
  @Test
  public void emptyTest() {
      Stack&lt;String&gt; stack = new Stack&lt;String&gt;();
      assertTrue(stack.isEmpty());
  }
  
  private static VirtualMachine attach(VirtualMachineDescriptor virtualMachineDescriptor) {
  
      VirtualMachine virtualMachine = null;
  
      try {
          virtualMachine = VirtualMachine.attach(virtualMachineDescriptor);
  
      } catch (AttachNotSupportedException anse) {
          System.out.println("Couldn't attach " + anse);
      } catch (IOException ioe) {
          System.out.println("Exception attaching or reading a jvm." + ioe);
      } 
  
      return virtualMachine;
  }
  
  private static VirtualMachineDescriptor getTestServerVM() {
  
      String name = "target/server-0.0.1-SNAPSHOT.jar";
      List&lt;VirtualMachineDescriptor&gt; vms = VirtualMachine.list();
  
      VirtualMachineDescriptor serverVM = vms.stream()
                .filter(vm -&gt; name.equals(vm.displayName()))
                .findAny()
                .orElse(null);
  
      System.out.println("Test server id : " + serverVM.id());
  
      return serverVM;
  }
  </code></pre>
  
  <p>Is this suffice or do i need to load the agent?
  I am asking this, because though program shows that Junit test class attached successfully, i see process id for Junit like this (by running <code>JCMD</code> command)-</p>
  
  <pre><code>3585 org.eclipse.jdt.internal.junit.runner.RemoteTestRunner -version 3 -port 55632 -testLoaderClass org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader -loaderpluginname org.eclipse.jdt.junit4.runtime -classNames JunitRnD.J
  </code></pre>