Saturday, January 8, 2011

Running a single test with JUnit and Eclipse

So, I had a slight problem with using TDD in Eclipse.  Not a problem as such, more an obstacle that I needed to overcome.  What I wanted to do was to write a test, get that working, then re-run all the tests, check that the changes to the code hadn’t caused another error to correct, then move on to the next test.  I found a few odds and ends about how this could be done, but nothing seemed to work.

After some looking and seeing I was able to get this working.  Here’s how I did it.  For this example, I am using JUnit 4 and Eclipse 3.6.1 (Helios).  Please note, to see the images more clearly just click on the image.

Firstly, go to Run –> Run Configurations

Then, right click the JUnit node in the tree and select New

Enter the name for the run configuration (I have called mine XMLSourceRepository_GetTokensTest)

Select the Method that you would like to test (default is all methods).

Now, I have Android JUnit and Eclipse JUnit launchers, so down the bottom I need to press the hyperlink and the following dialogue box appears. Select the Use Configuration specific settings and then Eclipse JUnit Launcher.

And your done.  Press the run button to run the test, and now it is in your run and debug button menus

So there you have it.  Using JUnit and Eclipse Helios (3.6.1) I have been able to select a single test to run without the overhead of other tests being run as well.

Now, to me, this is rather complex and time consuming if you write a test, change the run configurations to add or alter an existing configuration, make a few changes to change the code, then have to do the whole process again.  It would be easier be able to do this via the source or a test list of some kind.  I am not saying that this isn’t possible, but I couldn’t get it to work.  If you know how to do that, please let me know so that I can correct this post with the easier way of managing tests!

2 comments:

  1. Or you could do this:

    1. Do one full run of your tests
    2. Open the Junit view
    3. Right click on any test and choose run
    3a. [setup, single test, teardown runs]
    4. Click on the stop light looking icon top right of view, choose the previous run
    5. Right click on another test and choose run
    5a. [setup, a different single test, teardown runs]

    ReplyDelete
  2. Hi Peter,

    I tried that, and had a question. How can I re-run the same test using the keyboard? I usually hit CTRL + F11 to run my tests. If I use the method above, I can only re-run the test using the JUnit UI. Am I doing something wrong? Or is there a keyboard combo that will do what I want? I just like using the keyboard (especially on a laptop, the less mouse use the better).

    That said, I do like your method better, less config changes. I just like to use the keyboard to run the test...

    ReplyDelete