Useful code templates

I’m using Eclipse in my everyday work and it has really useful feature of code template (it is available in Window -> Preferences -> Java -> Editor -> Templates). Below you can see templates which I’m using most often while writing test cases. I’m using JUnit4 and Mockito.

  • RunWith annotation with MockitoJUnitRunner
    ${imp:import(org.mockito.runners.MockitoJUnitRunner)}
    @${testType:newType(org.junit.runner.RunWith)}(MockitoJUnitRunner.class)
    

    Output:

    import org.junit.runner.RunWith;
    import org.mockito.runners.MockitoJUnitRunner;
    
    @RunWith(MockitoJUnitRunner.class)
    
  • Logger
    ${:import(org.slf4j.Logger,org.slf4j.LoggerFactory)}
    private static final Logger log = LoggerFactory.getLogger(${enclosing_type}.class);
    

    Output:

    private static final Logger log = LoggerFactory.getLogger(type.class);
    
  • Test case with useful imports and with given/when/then sections
    ${staticImport:importStatic('org.junit.Assert.*','org.mockito.Mockito.*','org.hamcrest.Matchers.*','org.mockito.BDDMockito.*')}
    @${testType:newType(org.junit.Test)}
    public void should${testName}()
    {
    	// given
    	${cursor}
    
    	// when
    
    	// then
    
    }
    

    Output:

    import static org.hamcrest.Matchers.*;
    import static org.junit.Assert.*;
    import static org.mockito.BDDMockito.*;
    import static org.mockito.Mockito.*;
    
    @Test
    public void shouldtestName()
    {
    	// given
    
    	// when
    
    	// then
    
    }
    
  • Mock for specific type of object
    ${type} ${name} = ${:importStatic(org.mockito.Mockito.mock)}mock(${type}.class);
    

    Output:

    type name = mock(type.class);