Tutorial: how to create a JUnit test method template in NetBeans

NetBeans has a very nice feature: code templates.

Let me show how I use it to add a new JUnit test method in the test classes.

Go to Tools → Options → Editor → Code Templates and add the following template:

Abbreviation: te (this is only my proposal)

Expanded text:

@${baseType type="org.junit.Test" default="Test" editable="false"}
public void ${cursor}() {
    // given

    // when

    // then

}

2014-03-05_pic01Then go to a test class, type “te” (our template abbreviation) and press the TAB key.

See what’s happen:

2014-03-05_pic022014-03-05_pic03

First, the org.junit.Test include has been added (if not already in). This is thanks to the ${baseType} instruction we added in the template.

Second, the prompt is waiting for you for the method name. See ${cursor} instruction in the template.

Just write the name and we have complete test method template in our class.

2014-03-05_pic04

Of course, the template can be adjusted to your needs and habits.

Benefits:

  • we code faster
  • we have more uniform code style

NetBeans code template syntax is (partially) documented here.

About these ads

2 thoughts on “Tutorial: how to create a JUnit test method template in NetBeans

  1. Pingback: My 5 favorite NetBeans IDE features (vs. Eclipse) | Gualtiero Testa

  2. I tend not to leave a response, but after reading through
    some of the responses here Tutorial: how to create a JUnit test method template in NetBeans |
    Gualtiero Testa. I actually do have a few questions for you if
    you tend not to mind. Is it just me or does it look
    as if like some of these responses look like they are coming from
    brain dead people? :-P And, if you are posting on other places, I’d like to follow you.
    Could you list of all of all your social pages like your Facebook page, twitter feed, or linkedin profile?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s