如何将静态导入添加到IntelliJ IDEA实时模板

Mar*_*tör 5 java intellij-idea live-templates

我需要将以下Eclipse模板移植到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

}
Run Code Online (Sandbox Code Playgroud)

到目前为止我得到的是

/** 
 * 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

}
Run Code Online (Sandbox Code Playgroud)

然后勾选Shorten FQ names旗帜.

${staticImport:importStatic()}表达式的IDEA等价物是什么?

Jav*_*aru 7

您不能只在实时模板中导入静态导入.(您可以使用文件模板,请参阅下文).但是你可以在模板中使用方法.您只需完全限定该类,然后选择"缩短FQ名称"和"尽可能使用静态导入"选项.例如,以下内容:

org.junit.Assert.assertEquals("$END$", $EXPECTED$, $ACTUAL$);
Run Code Online (Sandbox Code Playgroud)

将导致:

import static org.junit.Assert.*;
. . .
assertEquals("my error message", myExpectedVar, myActualVar);
Run Code Online (Sandbox Code Playgroud)

在被调用时.(我将$EXPECTED$$ACTUAL$变量设置为variableOfType("")具有相应的默认值expected并且actual)

如果您希望在所有单元测试中包含某些静态导入,那么我建议编辑"类" 文件和代码模板.例如:

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

}
Run Code Online (Sandbox Code Playgroud)

但请记住,如果您启用了"动态优化导入"选项(在IDE设置>编辑器>自动导入中),则会立即删除静态导入,除非您还包含一个方法(或其他代码)使用静态导入.