Blog

Friday 22 November 2013

IntelliJ Idea Live templates for TDD

For those that practice TDD and love IntelliJ Idea we show how to speed up test scenario brainstorming.

When I started writing tests I immediately implemented first test that was coming to my mind. After 2 or 3 tests I was exhausted and inventing new test scenario was getting harder and harder. This is why I started brainstorming scenarios without getting into implementation details. I would simply create new test methods:
@Ignore("not implemented yet")
@Test
public void someTest() throws Exception {
//        Given
    
//        When
    
//        Then
    org.junit.Assert.fail("Not implemented yet");
}
in case of JUnit (Java) or
it("should expect something", function() {
    throw new Error("Not implemented yet"); 
});
in case of Jasmine (JavaScript).

The cool part is that IntelliJ's live templates allow me to create such signature with several keystrokes. I just type "nt" and then hit TAB and I've got entire signature.
Here is how to do it.

JUnit

First let's create template that will create test case signature for JUnit. Go to Idea's settings and select "Live templates" item in left hand side list. Select "other" group and press plus button ("Add"). Fill form with following data:
  • Abbreviation: nt 
  • Description: New test method 
  • Template text:
@org.junit.Ignore("Not implemented yet")
@org.junit.Test
public void $name$() throws Exception {
//        Given
    
//        When
    
//        Then
    org.junit.Assert.fail("Not implemented yet");
}
Select "Reformat according to style", "Use static import if possible" and "Short FQ names". Finally you have to select context in which this template is to be applied. Hit "Applicable in Change" link and select "Java->Declaration".

That's it.

Jasmine

The templates for Jasmine are a bit more complex. Let's create "iti" template that will create Jasmine test with AngularJS injection.
it("should something", inject(function($rootScope) {
    //your custom lines
}));
Create new template just like before with following template text:
it("should $summary$", inject(function($injections$) {
    $instruction$
}));
We want user to be able to write summary, hit enter, then injections and finally some instructions. We will provide default values so that user may simply hit Enter,Enter and go to inventing next test scenario. Hit "Edit variables" button and provide following values to "Expression" column:

  • summary: "..." 
  • injections: "$rootScope" 
  • instruction: "throw new Error(\"Not implemented yet\");"

I also have live templates for "it" (New Jasmine test) :
it("should $summary$", function() {
    $instruction$
});
and for "des" (New Jasmine test group) :
describe("$groupName$", function ()
{

});
Happy brainstorming!

No comments:

Post a Comment