Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eclipse junit test discovery

In eclipse - the junit test runner will find this test:

class Blah { 
    public static class Tests {
        [Test] void testOne() {}
}}

but it won't find this test

class Blah<T> { 
    public static class Tests {
        [Test] void testOne() {}
}}

Can anyone explain why, and is it possible to fix that in some way?

like image 936
Darren Oakey Avatar asked Jun 15 '26 05:06

Darren Oakey


2 Answers

I can't explain why eclipse won't accept generic classes to run as JUnit test. This might be a bug, but I could not find anything on the issue tracker.

There are now two ways to work around your problem. You can manually create a run-configuration for your test and start this. The other way is to use a test suite. Add a new class to your test-package containing the following

package com.prodyna.packetcapture.text;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

@RunWith(Suite.class)
@SuiteClasses({ Blah.class })
public class AllTests {

}

You can run this normally as JUnit-test and it will run all test classes that you specify in the SuiteClasses annotation.

like image 84
DKM Avatar answered Jun 17 '26 19:06

DKM


This is a bit of a strange one. Eclipse seems to be a bit inconsistent with this one.

First of all, we need to say that it doesn't really make sense to have a generic test like this. JUnit (and Eclipse) instantiates this class using reflection, so it doesn't care about the generic part. It probably won't work as you expect.

To explain the Eclipse part, Eclipse has two stages for executing a JUnit test: it detects whether or not the class is a JUnit test and it then executes it. It's the first part that is preventing you from running the test. If you create the generic test:

public class GenericTest<T> {
  @Test public void foobar() {
    System.out.println("GenericTest");
  }
}

Then the option 'Run as->JUnit test' isn't available on this class. If you remove the <T>, it becomes available and you can run it; it appears in the JUnit view. This is as you say.

The inconsistent part is when you put the back, you can now re-execute the test from the JUnit view.

Eclipse rerun JUnit test

So the execution of the test actually works when the class is generic. However, you can't execute it normally in Eclipse.

For info, the JUnit view can't really prevent you from doing this, because it stores the class name in the run configuration: see How does Eclipse actually run Junit tests?.

I don't think you'll get very far if you raise an issue, because as I said using a generic class in this way doesn't really make sense.

like image 29
Matthew Farwell Avatar answered Jun 17 '26 18:06

Matthew Farwell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!