ekj
ekj

Reputation: 1082

Launching a JUnit test from an eclipse plugin using a custom JUnit runner implementation

I have written a custom JUnit runner that I want to become part of an eclipse plugin that will launch tests using this runner without having to apply the @RunWith annotation to the class. I have managed to get an additional item under the 'Run As' context menu, using the org.eclipse.debug.ui.launchShortcuts extension point. However, I am not sure how to invoke the test using my custom runner.

Upvotes: 3

Views: 1429

Answers (1)

ekj
ekj

Reputation: 1082

So I figured out a way to do what I wanted. However, it does seem a bit hacky. But, I thought that I would post the answer here in case someone else runs into the same problem.

First you have to register a junit kind like this:

<extension point="org.eclipse.jdt.junit.internal_testKinds">
      <kind
            id="my.junit.kind"
            displayName="Your Kind Name" 
            finderClass="org.eclipse.jdt.internal.junit.launcher.JUnit4TestFinder"
            loaderPluginId="org.eclipse.jdt.junit4.runtime"
            loaderClass="your.test.loader.MyLoaderClass">
         <runtimeClasspathEntry pluginId="org.eclipse.jdt.junit4.runtime" />
         <runtimeClasspathEntry pluginId="org.eclipse.jdt.junit.core" />        
         <runtimeClasspathEntry pluginId="org.eclipse.jdt.junit.runtime"/>    
      </kind>
   </extension>

In the xml you have to specify a custom implementation of org.eclipse.jdt.internal.junit.runner.ITestLoaderwhich in turn returns an implementation of org.eclipse.jdt.internal.junit.runner.ITestReference. The core part is the implementation of ITestReference, because this is where you create an instance of your custom JUnit runner.

  public class MyTestReference extends JUnit4TestReference
   {

      public MyTestReference(final Class<?> p_clazz, String[] p_failureNames)
      {
         super(new Request()
         {
            @Override
            public Runner getRunner()
            {
               return new MyCustomRunner(p_clazz);
            }

         }, p_failureNames);
      }
...
}

Then finally you have to link this with a launch shortcut that sets the kind appropriately

public class MyJunitLaunchShortcut extends JUnitLaunchShortcut
{
   @Override
   protected ILaunchConfigurationWorkingCopy createLaunchConfiguration(IJavaElement p_element) throws CoreException
   {
      ILaunchConfigurationWorkingCopy config = super.createLaunchConfiguration(p_element);
      config.setAttribute(JUnitLaunchConfigurationConstants.ATTR_TEST_RUNNER_KIND, "my.junit.kind");
      return config;
   }
}

This does use a bunch of internal classes, so there is probably a better way. But this seems to work.

Upvotes: 3

Related Questions