Running JUnit from Vim

Normally when I’m programming in Java I’ll use Eclipse. However, in some cases Eclipse can be a bit heavyweight and I’ll fallback on Vim. The last time I did this I started to miss the ability to quickly and easily run unit tests on a per class basis. For this reason, I added the following function to my .vimrc which runs the appropriate test class for the current Java class.

function RunTest()

    let cla = matchstr(expand("%:p"), '^.*[/\\]src[/\\]\(test\|java\)[/\\]\zs.*')
    "still need to replace /s with .s
    let class = "java org.junit.runner.JUnitCore " .  strpart(substitute(cla, "/", "\.", "g"), 0, strlen(cla) -5)

    if match(class, "Test") == -1
        let class = class . "Test"
    endif

    echo class
    echo system(class)
endfunction

map <F6> <Esc>:echo RunTest()<CR>

The code assumes that your test directory structure mimics your source directory structure and all the names of your test classes are the same as the source classes with “Test” appended e.g. if you are editing “src/mypackage/MyClass.java”, it will attempt to run “test/mypackage/MyClassTest”. (If you are currently editing a test class, it should run that class).

I also mapped F6 as a shortcut to the function.

I really don’t know Vim script at all, so I’m sure the code could be a lot cleaner. Still, it was a big help for me, and I now find it quicker to run the correct test in Vim than Eclipse.

5 Responses to “Running JUnit from Vim”

  1. James Bauer Says:

    I love the script but when I run this with a default vim install it appears my JUnitCore jar can’t be found

    Getting the following

    java org.junit.runner.JUnitCore Test
    java.lang.NoClassDefFoundError: org/junit/runner/JUnitCore
    Caused by: java.lang.ClassNotFoundException: …

    the only other difference is that my test classes live under /src/test/etc
    and my implementation code lives under src/main/etc

  2. James Bauer Says:

    I actually found the answer was a simple -ref the class path to the junit jar and away you go

    http://stackoverflow.com/questions/5433228/how-to-add-a-class-path-in-vimscript/5459589#5459589

  3. Adrian Says:

    Yeah, it looked like a classpath issue, but it was hard to tell from here.

    I think I have junit on my default classpath, so I never had that issue.

  4. James Bauer Says:

    Just curious – how did you compile before the junit test runner took off? did you do a javac command to build the file w/ each dependency or use maven or ant?

  5. Adrian Mouat Says:

    I was using ant at the time.

Leave a Reply