If you haven’t tried vim-test yet, please do. It provides a consistent interface for running unit tests from within vim for a variety of languages and test runners. It also has support for different methods of dispatching your tests from vim to a terminal to retrieve the results.

vim-test works out of the box for a number of languages and is easily extensible to support additional languages. In fact, I recently contributed a Maven test runner for the Java language. If you are developing a Maven project, you can now run your tests from within vim using vim-test.

For anyone attempting to write their own vim-test runner, the source code enabling the Java version is provided here and copied below.

if !exists('g:test#java#maven#file_pattern')
  let g:test#java#maven#file_pattern = '\v^.*[Tt]est\.java$'
endif

function! test#java#maven#test_file(file) abort
  return a:file =~? g:test#java#maven#file_pattern
endfunction

function! test#java#maven#build_position(type, position) abort
  let strip_extension = split(a:position['file'], "\.java")[1]
  let filename = split(strip_extension, "/")[-1]

  if a:type == 'nearest'
    let name = s:nearest_test(a:position)
    if !empty(name)
      return [name]
    else
      return [filename]
    endif
  elseif a:type == 'file'
    return [filename]
  else
    return []
  endif
endfunction

function! test#java#maven#build_args(args) abort
  let args = ['-Dtest='] + a:args
  return [join(args, "")]

endfunction

function! test#java#maven#executable() abort
  return 'mvn test'
endfunction

function! s:nearest_test(position) abort
  let name = test#base#nearest_test(a:position, g:test#java#patterns)
  return escape(join(name['namespace'] + name['test'], '#'), "#")
endfunction