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

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • JUnit 5 Custom TestListeners
  • How to Test Gradle Plugins
  • Spring 5 Web Reactive: Flux, Mono, and JUnit Testing
  • Creating a Web Project: Refactoring

Trending

  • How To Replicate Oracle Data to BigQuery With Google Cloud Datastream
  • Measuring the Impact of AI on Software Engineering Productivity
  • Beyond Microservices: The Emerging Post-Monolith Architecture for 2025
  • AI-Assisted Coding for iOS Development: How Tools like CursorAI Are Redefining the Developer Workflow
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. Test Driven Development Using TestNG, Gradle

Test Driven Development Using TestNG, Gradle

Basic Approach to start with TDD. Simple example using Java, TestNG, Jacoco and Gradle

By 
Subhasis Roy user avatar
Subhasis Roy
·
Sep. 08, 20 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
5.0K Views

Join the DZone community and get the full member experience.

Join For Free

What Is TDD?

Test Driven Development is a process where developers write the test case first and then run the test case to fail. Then, they gradually write the minimum corresponding code needed to successfully execute the test cases and then finally refactors the new code to acceptable standards.

Test driven developmentJust to summarize the following is the sequence of steps in TDD approach.

  • Add a test.
  • Run all tests and see if it fails.
  • Write some code.
  • Re-Run tests.
  • Refactor code.
  • Repeat.

Benefits of TDD:

The following are the benefits of TDD approach.

  • TDD Forces to write simple code.
  • Development costs and time are reduced.
  • Test cases become safety net for code.
  • Codes become almost bug free (if done correctly).
  • Improves code quality.
  • Easy maintenance.

Create Java - Gradle Project

In this below example, we are going to see a basic example of writing test cases and then gradually writing the corresponding class to make the test cases run successful.

Also, we will see how to integrate the Jacoco plugin in Gradle to create the test result report.

Prerequisites

You should have Java Development Kit (JDK) and Gradle build tool installed on your system. Here, I am using JDK 1.8 and Gradle 6.5 for this example.

First, you can create a Java Gradle project using IntelliJ or Eclipse.

Once you open the build.gradle file in your project it will have the basic configurations for a Java project and the file will look like below.

Groovy
xxxxxxxxxx
1
15
 
1
plugins {
2
    id 'java'
3
    id 'jacoco'
4
}
5
6
group 'sample.tdd.demonstration'
7
version '1.0-SNAPSHOT'
8
9
sourceCompatibility = 1.8
10
11
repositories {
12
    mavenCentral()
13
}
14
15
dependencies {}  


Adding the TestNG Dependency in Gradle

You can find your desired TestNG version in https://mvnrepository.com/artifact/org.testng/testng. Add the dependency to your build.gradle file as below snippet. 

Here, I am using version 7.1.0, but you can use any version of your choice.

Groovy
xxxxxxxxxx
1
 
1
dependencies {
2
    compile group: 'org.testng', name: 'testng', version: '7.1.0'
3
} 

Enable the TestNG Support

After adding the dependency, you should enable the support for TestNG in build.gradle file.

Groovy
xxxxxxxxxx
1
 
1
test {
2
    // enable TestNG support 
3
    useTestNG()    
4
}


Now, we are set to go, but we also want to see our test results are logged to the console. So, to do that, we need to add one more option testLogging under this "test" section as below.

Here, we have used the option to show results in console for PASS, FAILED and SKIPPED test cases.

Groovy
xxxxxxxxxx
1
 
1
test {
2
    // enable TestNG support 
3
    useTestNG()  
4
    // enable console logging of test results
5
    testLogging {
6
        events "PASSED", "FAILED", "SKIPPED"
7
    }
8
}


Basic Example of the TDD Approach

Suppose you have given a scenario of writing an email validation functionality. 

We already have added TestNG in our project and enabled the support. Now, we are all set for our first TDD approach to develop the above functionality.

First, we need to write one test class under "src\test\java" pkg in your project. Let's say I have given the name as "EmailValidateTest.java"(this can be any name).

Java
xxxxxxxxxx
1
10
 
1
import org.testng.Assert;
2
import org.testng.annotations.Test;
3
4
public class EmailValidateTest {
5
    @Test
6
    public void testEmailAddress(){
7
        EmailValidator emailValidateObj = new EmailValidator();   
8
        Assert.assertEquals(true,emailValidateObj.isValidEmail("example@email.com"));
9
    }
10
}


If you notice carefully, in the above code I have mentioned a class "EmailValidator.java", it is the class which we are going to write, along with the isValidEmail method inside it.

While writing the test class, we already decided/thought that this above class and method will contain the original code for the email validation functionality.

Also if you look carefully at Line no 8, we are using Assert. It's a class with different function, in TestNG API which helps to verify the conditions of the test and decide whether test has failed or passed. 

To know more about TestNG classes and functions, you can refer to TestNG 7.1.0 API

Now to make this above test case run successfully, we should write the "EmailValidator.java" under "src\main\java" pkg, along with the implementation of email validation logic.

Java
xxxxxxxxxx
1
14
 
1
import java.util.regex.Matcher;
2
import java.util.regex.Pattern;
3
4
public class EmailValidator {
5
    private static final String VALID_EMAIL_REGEX = "^[\\w-\\+]+(\\.[\\w]+)*@[\\w-]+(\\.[\\w]+)*(\\.[a-z]{2,})$";
6
    private static Pattern eMailPattern = Pattern.compile(VALID_EMAIL_REGEX, Pattern.CASE_INSENSITIVE);
7
8
    private Matcher matcher;
9
10
    public boolean isValidEmail(String email) {
11
        matcher = eMailPattern.matcher(email);
12
        return matcher.matches();
13
    }
14
}


Run the Test Case 

Now, if you run the test class, you can see that the test case ran successfully in console.

Test classes

What Is Jacoco?

Jacoco is a free code coverage library for Java. It helps in visual representation and helps in analyzing code coverage report. In simple terms, it's a code coverage report generator plugin.

Adding Jacoco in Gradle

You can add the Jacoco plugin in build.gradle file as below snippet. The below part you should add on top of your existing build.gradle file content.

Below, I have just shown the part which is required to include the Jacoco plugin.

Groovy
xxxxxxxxxx
1
21
 
1
plugins {
2
    id 'jacoco'
3
}
4
5
jacoco {
6
    toolVersion = "0.8.5"
7
}
8
9
test {
10
    // report is always generated after tests run
11
    finalizedBy jacocoTestReport 
12
}
13
14
jacocoTestReport {
15
    // tests are required to run before generating the report
16
    dependsOn test 
17
    reports {
18
        //destination directory of test case report 
19
        html.destination file("${buildDir}/jacocoHtml")
20
    }
21
}


Re-run Your Test Case

Now, if you run the "EmailValidateTest.java" file to run the test case, you can see one "jacocoHtml" folder got created inside "build" directory.

jacocoHTML folder

If you open the index.html file in your web browser, you can see the visual representation of your code coverage of of the original functionality. 

In the below image, you can see that the inValidEmail test function is properly executed with 100% code coverage.

Email Validator test coverage

If you click on the isValidEmail hyperlink in the report, it will show you the original class and method in details. In the below image, you can see that the main logic of email validation code is properly covered and tested during our test case run.

EmailValidator class

Conclusion

The benefits of test-driven development more than normal development approaches. It helps in writing a standard, flexible and modular code within very short time of development. Codes are very much cleaner, and almost bug free and very easily maintainable.

Testing Test-driven development TestNG Gradle Test case Code coverage Java Development Kit Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • JUnit 5 Custom TestListeners
  • How to Test Gradle Plugins
  • Spring 5 Web Reactive: Flux, Mono, and JUnit Testing
  • Creating a Web Project: Refactoring

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!