DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • My Experiences with Maven in IntelliJ IDEA and NetBeans IDE
  • Hack OpenJDK with NetBeans IDE
  • Driving DevOps With Smart, Scalable Testing
  • Unit Testing Large Codebases: Principles, Practices, and C++ Examples

Trending

  • Navigating Change Management: A Guide for Engineers
  • Enhancing Business Decision-Making Through Advanced Data Visualization Techniques
  • Using Python Libraries in Java
  • Can You Run a MariaDB Cluster on a $150 Kubernetes Lab? I Gave It a Shot
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. How To Do Unit Testing Using JUnit4 on Netbeans IDE

How To Do Unit Testing Using JUnit4 on Netbeans IDE

Developers and testers can learn how to use the JUnit testing framework for unit testing with the NetBeans IDE to improve code quality in this tutorial.

By 
Tarun Telang user avatar
Tarun Telang
DZone Core CORE ·
Updated Aug. 05, 22 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
25.8K Views

Join the DZone community and get the full member experience.

Join For Free

Why "Hello World" for JUnit?

This article is intended for Java developers with basic knowledge of core Java and Object Oriented Principles. You need not be familiar with the JUnit framework or NetBeans IDE to follow this article.

This article provides an introduction to the test-first or test-driven development (TDD) philosophy which recommends that unit testing and coding should go hand-in-hand to ensure the stability of your code.

This is an actionable article that guides a user to write a very simple unit test while developing a simple application. It would hardly take 10 minutes for a beginner-level Java developer to try out the code in this article.

Generally, it takes a couple of years for a Java developer working on professional projects to appreciate the benefits of writing unit tests for his/her code. Even the NetBeans documentation on creating Unit tests requires familiarity with Java Collections classes. This article demonstrates the benefit of Unit testing with very less effort and would immediately encourage developers in getting into the habit of writing unit tests simultaneously with production code.

What Is JUnit?

JUnit is a simple, free and open-source framework to write repeatable unit tests using Java. Erick Gamma and Kert Beck originally wrote it. It is a regression-testing framework, which allows the developer to write code faster with high quality. JUnit tests increase the stability of the software.

The main philosophy behind this testing framework is to make coding and testing move hand in hand.

What Is Netbeans IDE?

In this article, we will apply this philosophy of testing and coding side by side to an object-oriented version of the Hello World program by creating a test case for it in NetBeans IDE. NetBeans IDE is the official IDE for Java 8 for the development of desktop, mobile, and web applications, as well as HTML5 (including Oracle JET) applications with HTML, JavaScript, and CSS.

Let us apply this philosophy of testing and coding side by side to the object-oriented version of the Hello World program by creating a test case for it in NetBeans IDE v8.2. It is available for free download here.

How To Write Java Test Classes Using Netbeans IDE

Please follow the steps below:

1.  Launch NetBeans IDE. In Windows 10, it can be started using   > NetBeans > NetBeans 8.2 IDE.

2.  In the IDE, choose File > New Project, as shown in the figure below.

File > New Project

3. In the New Project wizard, expand the Java category and select Java Application as shown in the figure below. Then click Next.

New Project Wizard

4. In the Name and Location page of the wizard, do the following (as shown in the figure below):

  • In the Project Name field, type HelloWorld.
  • Check the Use Dedicated Folder for Storing Libraries checkbox.
  • In the Create Main Class field, type com.dzone.example.HelloWorld

New Java Application > Name and Location

5. Click Finish to create the project.

6. Now go to the Context menu of the project and Select New > Java Class to create a new Java class.

Create a new Java class

7. Type in the following code for the class.

package com.oracle.hgbu.example;

/** 
 * An Object Oriented Hello World Program.  
 * @version 1.0 
**/
public class HelloWorld {  
  private String hello; 
  private String world;         

  /**         
  * Constructor         
  */ 
  HelloWorld(){  
    hello = “Hello”;  
    world = “World”; 
  } 

  /**
  * forms the Hello World Message.          
  */        
  public String formMessage(){ 
 String message;  
    message = hello + ” ” +  world;  
    return message; 
  } 

  public static void main(String[] args) {  
    HelloWorld helloWorld = new HelloWorld();  
    System.out.println(helloWorld.formMessage()); 
  }
}


8. Now select New File from the context menu of the project and choose Test for Existing Class.

Test for existing class

9. Enter the following details and click Next.

New test for existing class > Finish

See below the project structure for your reference.

Project structure dropdown

10. Now select the HelloWorld.java from Browse… as shown in the figure below, and click Finish.

Select the HelloWorld.java from Browse… as shown in the figure below, and click Finish

11. Write the following code for the HelloWorldTest class.

package com.oracle.hgbu.example;

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

/**
 * Test class for HelloWorld 
 * @version 1.0
 */
public class HelloWorldTest {

    HelloWorld helloWorldInstance;

    @Before
    public void setUp() {
        System.out.println("* HelloWorldTest: Before method setUp()");
        helloWorldInstance = new HelloWorld();        
    }

    @After
    public void tearDown() {
        System.out.println("* HelloWorldTest: After method tearDown()");
        helloWorldInstance = null;
    }    
    /**         
    * unit test for formMessage method.         
    */    
    @Test
    public void testFormMessage() {
        //Asserts that two Strings are equal                
        String expResult = "Hello World!";
        String result = helloWorldInstance.formMessage();
        System.out.println("* HelloWorldTest: test method 1 testFormMessage()");
         Assert.assertEquals(expResult, result);
    }   
}


12. Select Test from the context menu of the project or press (Alt + F6).

Select Test from the context menu

Congrats! The green bar indicates that the test is successful. If the test case fails, a red bar and error message are displayed.

13. Now select Run from the context menu of the project to Run the Hello World Program.

Run the Hello World Program

The string “Hello World” is printed to the console. This finishes the Hello World program with Unit Test in NetBeans IDE.

What Are JUnit Best Practices? 

Below are some of the best practices I would recommend while using JUnit in production:

  • Run all the tests in the system at least once per day (or night).
  • If you find yourself debugging using System.out.println(), better write a test to automatically check the result instead.
  • When a bug is reported, write a test to expose the bug.
  • Write unit tests before writing the code and only write new code when a test is failing.

In the next article, I would be writing about more tips and tricks for improving your code quality.

Integrated development environment NetBeans unit test

Opinions expressed by DZone contributors are their own.

Related

  • My Experiences with Maven in IntelliJ IDEA and NetBeans IDE
  • Hack OpenJDK with NetBeans IDE
  • Driving DevOps With Smart, Scalable Testing
  • Unit Testing Large Codebases: Principles, Practices, and C++ Examples

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!