In Intellij, how do I create a live template that adds import statements for tests?
intellij-idea, java, junit
Solution
You can create a live template for `test` in IntelliJ 12 like so:
File > Settings... > Live Templates
- Add a new template
- Set the abbreviation (what you'll type to use this filter)
Type this template (after pressing tab, your cursor will be at $EXPR$ to finish the name of the method, in this case, and $END$ is where the cursor will be after completing the $EXPR$ name (i.e., pressing enter)
@org.junit.Test
public void test$EXPR$() {
$END$
}
- Ensure Expand with is set to Tab (or whichever you prefer)
- Ensure Shorten Fully Qualified names is enabled (that way `@org.junit.Test` in the template adds `import org.junit.Test;` to the top of the file and the method will have just `@Test`)
- Set the Applicable to "in Java: declaration".
Edit: as tieTYT points out, the the `import static junit.framework.Assert.*` part can be satisfied by creating a new File Template:
#if (${PACKAGE_NAME} && ${PACKAGE_NAME} != "")package ${PACKAGE_NAME};#end
import static junit.framework.Assert.*;
#parse("File Header.java")
public class ${NAME}
{
}
The above is just copy-pasted from the Class template, adding the `import` statement.
Problem
I'd like to be able to type `test` in a class file and then press tab and have that expand to: ``` @Test public void whenThen() { } ``` And also include appropriate imports. This includes `import static junit.framework.Assert.*;`. How do I do this? I'm using Intellij 12