Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Intellij, how do I create a live template that adds import statements for tests?

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

like image 335
Daniel Kaplan Avatar asked Mar 08 '13 01:03

Daniel Kaplan


People also ask

How do I automatically import imports in IntelliJ?

Automatically add import statements You can configure the IDE to automatically add import statements if there are no options to choose from. In the Settings/Preferences dialog ( Ctrl+Alt+S ), click Editor | General | Auto Import. Select the Add unambiguous imports on the fly checkbox, and apply the changes.

What is a live template?

Use live templates to insert common constructs into your code, such as loops, conditions, various declarations, or print statements. To expand a code snippet, type the corresponding template abbreviation and press Tab . Keep pressing Tab to jump from one variable in the template to the next one.

How do I create a project template in IntelliJ?

From the main menu, select File | New Projects Setup | Save Project as Template. In the dialog that opens, name the template and configure the options: Save: if the project contains more than one module, select whether you want to create a template from the whole project or from one of the modules.


1 Answers

You can create a live template for test in IntelliJ 12 like so:

File > Settings... > Live Templates

Adding a template

  1. Add a new template
  2. Set the abbreviation (what you'll type to use this filter)
  3. 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$
    }
    
  4. Ensure Expand with is set to Tab (or whichever you prefer)
  5. 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)
  6. 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:

JUnit Test 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.

like image 132
kuporific Avatar answered Oct 21 '22 18:10

kuporific