javaintellij-idealive-templates

How to add static imports to IntelliJ IDEA live template


I need to port the following Eclipse template to IntelliJ IDEA

/**
 * See method name.
 */
@${testType:newType(org.junit.Test)}
public void should${testdesc}() {
  // given ${cursor}
  ${staticImport:importStatic('org.hamcrest.Matchers.*', 'org.junit.Assert.*', 'org.mockito.BDDMockito.*')} 
  // when

  // then

}

What I've got so far is

/** 
 * See method name.
 */
@org.junit.Test
public void should$EXPR$() { 
  // given $END$ 
  ${staticImport:importStatic('org.hamcrest.Matchers.*', 'org.junit.Assert.*', 'org.mockito.BDDMockito.*')} 
  // when 

  // then

}

And then tick the Shorten FQ names flag.

What's the IDEA equivalent for the ${staticImport:importStatic()} expression?


Solution

  • You cannot just import the static imports in a live template. (You can for a file template, see below). But you can when using a method in the template. You just simply fully qualify the class and then select both the "Shorten FQ names" and "Use static import if possible" options. For example, the following:

    org.junit.Assert.assertEquals("$END$", $EXPECTED$, $ACTUAL$);
    

    Will result in:

    import static org.junit.Assert.*;
    . . .
    assertEquals("my error message", myExpectedVar, myActualVar);
    

    when invoked. (I have the $EXPECTED$ and $ACTUAL$ variables set to variableOfType("") with corresponding default values expected and actual)

    If you want certain static imports to be included in all your unit tests, then I would recommend editing the "Class" File and Code Template. For example:

    package ${PACKAGE_NAME};
    
    #if ($NAME.endsWith("Test"))
    import static org.junit.Assert.*;
    import static org.hamcrest.Matchers.*;
    import static org.mockito.BDDMockito.*;
    #end
    
    #parse("File Header.java")
    public class ${NAME} 
    {  
    
    #if ($NAME.endsWith("Test"))
        // Add any default test methods or such you want here.
    #end
    
    }
    

    Keep in mind however, the static import will immediately be removed if you have the "Optimize imports on the fly" option (in IDE Settings > Editor > Auto import) turned on, unless you also include a method (or other code) that makes use of the static import.