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.
March 21st, 2011 at 9:04 pm
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
March 28th, 2011 at 2:29 pm
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
March 28th, 2011 at 6:20 pm
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.
March 29th, 2011 at 2:13 pm
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?
March 29th, 2011 at 6:57 pm
I was using ant at the time.