Tuesday, April 07, 2009

Run a single JUnit test method in Eclipse

Goes to show you, that you can teach an old dog new tricks. After years of using Eclipse I stumbled across a feature I am sure has existed since the glory days of Visual Age.

I had added yet another test method to a large JUnit TestCase class. I wanted to just run and re-run the new method 'til I had it just right without having to run all the other methods as well.

Yes of course, I could comment out all the other methods or just remove the @Test annotation. Back in the JUnit 3 days we have all -- at one time or another -- disabled tests by changing the "test" prefix of the test methods.

Somehow today, all these seemed abhorrent.

I wondered what would happen if I simply highlighted the method I wanted to test, and selected Run As > JUnit Test from the context menu.

Voila! That was the ticket!! It ran just the test I had wanted run.

As a bonus it even added TestCase.method_name as a "Run Configuration" for ease of future use.



  1. What Version of Eclipse?
    With my Version: 3.3.2
    Build id: M20080221-1800
    this does not work. :-(

  2. Jürgen:
    I am using Eclipse 3.4.1 (Build id: M20080911-1700)


  3. It is rather the choice of Test Runner.
    Single Test of a method doesn't work with JUnit 4
    It works with JUnit 3

    Eclipse 3.4.2
    Right click Test method
    Choose Run As > Run Configurations...

    On Test Tab
    Make sure "Run a Single test" radio is checked
    "Test Runner" drop down select JUnit 3 instead of JUnit 4


  4. This is a good post on Junit.


  5. I had the same problem as Jurgen with JUnit 4 and Eclipse 3.4.1 -- couldn't run single test. But I found a suggestion somewhere else that resolved the problem. My test class was still extending junit.framework.TestCase. When I stopped extending TestCase, everything worked fine and I was able to run single JUnit tests with the JUnit 4 test runner. Of course, I needed to JUnit 4 annotations use static imports for the assert methods, but I had already done that -- I had just not removed the TestCase inheritance.

  6. I tried to run a test case method and it gives me a class not found exception on the test class. I verified the class had been compiled by locating the class file. Anyone have any thoughts here?

    I tried what the other Anon wrote, but no luck. I also think that is a weird way to go.

  7. This is so cool. In Visual Studio you have such a feature, I was looking for it here and, yes, it is, it really is.

    Thanks for sharing this!


Tweety thoughts

    follow me on Twitter