Archive for June, 2009
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.