如何在IntelliJ IDEA的代码模板中添加静态导入

6
我需要将以下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

}

我目前得到的是:
/** 
 * 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

}

然后勾选 缩短FQ名称 标志。

${staticImport:importStatic()} 表达式在 IDEA 中有什么等效的呢?

2个回答

10

在Live Template中,您不能仅仅导入静态导入。 (对于文件模板,可以参见下面). 但是在模板中使用方法时,您可以完全限定类,然后选择"缩短FQ名称"和"尽可能使用静态导入"选项。例如,以下内容:

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

将导致:

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

在调用时(我已将$EXPECTED$$ACTUAL$变量设置为具有相应默认值expectedactualvariableOfType(“”))。

如果您想在所有单元测试中包含某些静态导入,则建议编辑“Class”文件和代码模板。例如:

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

}

需要记住的是,如果您打开了IDE设置中的“编辑器”>“自动导入”>“即时优化导入”选项("Optimize imports on the fly"),静态导入将被立即删除,除非您还包括使用静态导入的方法(或其他代码)。


这正是我在谷歌搜索“assertEquals live template”时想要的,而且这是一个非常好的答案。 - Ajax

1
现在可以使用静态导入添加实时模板:

您必须在选项中检查静态导入

@org.junit.Test
public void should$EXPR$when$CONDITION$() {
    org.junit.Assert.assertThat(null, org.hamcrest.CoreMatchers.is(org.hamcrest.CoreMatchers.nullValue())); 
}

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接