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:


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.


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


  • we code faster
  • we have more uniform code style

NetBeans code template syntax is (partially) documented here.

7 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? 😛 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?

  3. Hi Gualtiero,
    I could not get my version of a test template going nicely and then I found yours.
    I’ve sent in a feature request : https://netbeans.org/bugzilla/show_bug.cgi?id=251158

    Apologies if the junit part is a pure copy and paste of this, did not mean to plagiarise :-/
    It would be a very good standard addition to Netbeans and works almost like the IntelliJ template.


  4. Thanks Gualtiero.
    Can you please comment on the issue.
    I think @markiewb is worried about the copyright stuff.

    I would love to see the feature as standard in 8.1 🙂

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s