TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: How to Convert Maven Project to TestNG in Eclipse
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Selenium Tutorial

How to Convert Maven Project to TestNG in Eclipse

Last updated: Feb 25, 2024 10:55 am
By Meenakshi Agarwal
Share
13 Min Read
Convert Maven Project to TestNG in Eclipse
SHARE

Maven and TestNG are powerful tools in the Java ecosystem that streamline project management and testing processes, respectively. Integrating TestNG into a Maven project can enhance test automation capabilities, allowing for more robust and efficient testing. In this tutorial, we’ll explore the step-by-step process of converting a Maven project to use TestNG in Eclipse. We’ll cover various aspects, including project setup, dependencies, configuration, and examples to help readers understand the process thoroughly.

Contents
Step 1: Create a Maven Project in Eclipse If Not Already Have ItStep 2: Add TestNG Dependency to the POM.xmlStep 3: Update Project ConfigurationStep 4: Create a TestNG ClassStep 5: Run TestNG TestsAdditional Configuration: TestNG XML SuiteParameter Tests with TestNGTestNG ListenersParallel Execution with TestNGData Testing with TestNG Data ProvidersCommand LineManual Configuration in Eclipse

Convert Maven Project to TestNG in Eclipse

Before we begin, make sure you have the following prerequisites installed on your system:

  1. Eclipse IDE: Download and install the latest version of Eclipse IDE for Java Developers from the official Eclipse website.
  2. Java Development Kit (JDK): Ensure that you have the latest version of JDK installed on your machine. You can download it from the Oracle website or use OpenJDK.
  3. Maven: Install Maven by following the instructions on the official Apache Maven website.
  4. TestNG Plugin for Eclipse: Install the TestNG plugin for Eclipse to leverage its testing features. You can install it via the Eclipse Marketplace or by using the update site.

Step 1: Create a Maven Project in Eclipse If Not Already Have It

Start by creating a new Maven project in Eclipse. Follow these steps:

  1. Open Eclipse IDE.
  2. Select File -> New -> Other.
  3. In the “Select a wizard” dialog, choose Maven -> Maven Project and click Next.
  4. Select the checkbox for “Create a simple project (skip archetype selection)” and click Next.
  5. Enter the Group ID and Artifact ID for your project. For example, you can use com.example (as the Group ID) and MyTestProject (as the Artifact ID). Click Finish to create the Maven project.

Now, you have a basic Maven project in Eclipse.

Also See: Create Your First Selenium Maven Project

Step 2: Add TestNG Dependency to the POM.xml

The next step is to add TestNG as a dependency in the project’s pom.xml file. This file manages project configurations and dependencies. Open the pom.xml file and add the following dependency:

<dependencies>
    <!-- Other dependencies may be present -->
    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>7.4.0</version> <!-- Use the latest version available -->
        <scope>test</scope>
    </dependency>
</dependencies>

This XML snippet adds the TestNG dependency to your Maven project. Save the file, and Eclipse will automatically download the TestNG library.

Step 3: Update Project Configuration

Now that TestNG is added to the project, update the project configuration to enable TestNG support. Follow these steps:

  1. Right-click on your project in Eclipse.
  2. Select Properties -> Java Build Path.
  3. In the “Libraries” tab, click Add Library.
  4. Choose TestNG from the list and click Next.
  5. Select the checkbox for the test source folder and click Finish.
  6. Click Apply and Close to save the changes.

Enhance Your Knowledge: Check Out the Latest TestNG Interview Questions

Step 4: Create a TestNG Class

Now, let’s create a TestNG class to see how it integrates with the Maven project. Follow these steps:

  1. Right-click on the src/test/java folder in your project.
  2. Select New -> Other.
  3. Choose TestNG -> TestNG Class and click Next.
  4. Enter a name for your test class, e.g., SampleTest, and click Finish.

This will create a basic TestNG class with a sample test method.

import org.testng.annotations.Test;

public class SampleTest {
    @Test
    public void sampleTest() {
        System.out.println("This is a sample TestNG test.");
    }
}

Step 5: Run TestNG Tests

Now that we have a TestNG class, let’s run the TestNG tests to ensure everything is set up correctly:

  1. Right-click on the TestNG class (SampleTest in this case).
  2. Select Run As -> TestNG Test.
  3. Check the Console tab in Eclipse to see the test execution output.

You should see the output indicating that the TestNG test ran successfully.

Additional Configuration: TestNG XML Suite

TestNG allows you to configure test suites using an XML file. This is beneficial when you have multiple test classes or want to organize your tests efficiently. Create a testng.xml file in the project root and add the following content:

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="TechBeamersSuite">
    <test name="MyTest">
        <classes>
            <class name="com.example.SampleTest"/>
            <!-- Add more classes if needed -->
        </classes>
    </test>
</suite>

Now, you can run the test suite by right-clicking on the testng.xml file and selecting Run As -> TestNG Suite.

So far, in the above section, we covered how to convert a Maven project to use TestNG in Eclipse. We started by creating a Maven project, adding TestNG as a dependency, and configuring the project to support TestNG. We then created a sample TestNG class and executed a basic test. Additionally, we explored the use of TestNG XML suites for organizing tests efficiently.

By integrating TestNG into your Maven project, you gain the benefits of a powerful testing framework, enabling you to write and execute tests with ease. This combination improves the overall testing experience and results in a more robust and reliable Java application.

Let’s delve into this topic further and understand how can we utilize TestNG to enhance our project.

Parameter Tests with TestNG

TestNG allows parameterizing test methods, enabling the execution of the same test with different sets of data. Let’s modify our SampleTest to include a parameter test:

import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

public class SampleTest {
    @Test
    @Parameters("param")
    public void paramTest(String param) {
        System.out.println("Parameter Test with param: " + param);
    }
}

Now, create a testng.xml file that includes the parameter:

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="TechBeamersSuite">
    <test name="MyTest">
        <parameter name="param" value="Hello, TestNG!"/>
        <classes>
            <class name="com.example.SampleTest"/>
        </classes>
    </test>
</suite>

Run the testng.xml as a TestNG Suite to see how parameterized tests work.

TestNG Listeners

TestNG provides listeners that allow you to perform custom actions before or after certain events during the test execution. Let’s create a simple listener that prints a message before and after each test method:

import org.testng.ITestResult;
import org.testng.TestListenerAdapter;

@FunctionalInterface
interface ResultCheck {
    void handle(ITestResult out);
}

public class TechBeamers extends TestListenerAdapter {

    private void printOut(ITestResult out, ResultCheck handle) {
        handle.handle(out);
    }

    @Override
    public void onTestStart(ITestResult out) {
        printOut(out, r -> System.out.println("Starting Test: " + r.getName()));
    }

    @Override
    public void onTestSuccess(ITestResult out) {
        printOut(out, r -> System.out.println("Test Passed: " + r.getName()));
    }

    @Override
    public void onTestFailure(ITestResult out) {
        printOut(out, r -> System.out.println("Test Failed: " + r.getName()));
    }

    // Example of how you could use this with other events
    public void onTestSkipped(ITestResult out) {
        printOut(out, r -> System.out.println("Test Skipped: " + r.getName()));
    }
}

Add the listener to your testng.xml:

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="TechBeamersSuite">
    <test name="MyTest">
        <listeners>
            <listener class-name="com.example.TechBeamers"/>
        </listeners>
        <classes>
            <class name="com.example.SampleTest"/>
        </classes>
    </test>
</suite>

Now, when you run your tests, you’ll see additional messages indicating the test lifecycle events.

Parallel Execution with TestNG

TestNG supports parallel test execution, allowing you to run tests concurrently for faster results. Update your testng.xml to include parallel execution settings:

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="TechBeamersSuite" parallel="tests" thread-count="2">
    <test name="MyTest">
        <!-- Same config as before -->
    </test>
    <!-- Add more <test> elements for additional parallel tests -->
</suite>

This config enables parallel execution of tests with two threads. Adjust the thread-count attribute based on your machine’s capabilities.

Data Testing with TestNG Data Providers

TestNG supports data testing through data providers. Let’s modify our SampleTest class to include a data test:

import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class SampleTest {
    @Test(dataProvider = "testData")
    public void dataTest(String data) {
        System.out.println("Data Test with data: " + data);
    }

    @DataProvider(name = "testData")
    public Object[][] testData() {
        return new Object[][]{
                {"Data Set 1"},
                {"Data Set 2"},
                // Add more data sets as needed
        };
    }
}

Update your testng.xml to run the data-driven test:

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="TechBeamersSuite">
    <test name="MyTest">
        <classes>
            <class name="com.example.SampleTest"/>
        </classes>
    </test>
</suite>

This example illustrates the basics of data-driven testing using TestNG data providers.

Alternative Methods to Convert a Maven Project to TestNG

Let’s now explore an alternative approach to convert a Maven project to TestNG in Eclipse using the command line and also through manual configuration in Eclipse without using the TestNG Eclipse plugin.

Command Line

If you prefer using the command line, you can execute TestNG tests directly without relying on the Eclipse TestNG plugin. Follow these steps:

  1. Compile and Package the Maven Project: Open a terminal/command prompt and navigate to the root directory of your Maven project. Run the following command to compile and package the project:
   mvn clean install
  1. Run TestNG Tests: Once the project is built successfully, you can run the TestNG tests using the following command:
   mvn test

Maven will discover and execute the TestNG tests in your project. This approach is independent of the Eclipse IDE and is useful for continuous integration or command-line-driven test executions.

Manual Configuration in Eclipse

If you prefer not to use the TestNG Eclipse plugin or face issues with it, you can manually configure your Maven project in Eclipse to run TestNG tests. Follow these steps:

  1. Create a TestNG XML File: Manually create a testng.xml file in the root of your project. Define the test suite and include the classes you want to run. For example:
   <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
   <suite name="TechBeamersSuite">
       <test name="MyTest">
           <classes>
               <class name="com.example.SampleTest"/>
               <!-- Add more classes if needed -->
           </classes>
       </test>
   </suite>
  1. Configure Eclipse to Run TestNG XML:
  • Right-click on the testng.xml file in Eclipse.
  • Select Run As -> TestNG Suite. This will execute the TestNG tests based on the configuration specified in the XML file.
  1. Optional: Configure Maven Surefire Plugin: Open your project’s pom.xml file and add the Maven Surefire Plugin configuration to ensure that Maven recognizes TestNG tests. Add the following plugin configuration to the <build> section:
   <build>
       <plugins>
           <plugin>
               <groupId>org.apache.maven.plugins</groupId>
               <artifactId>maven-surefire-plugin</artifactId>
               <version>3.0.0-M5</version> <!-- Use the latest version available -->
               <configuration>
                   <suiteXmlFiles>
                       <suiteXmlFile>testng.xml</suiteXmlFile>
                   </suiteXmlFiles>
               </configuration>
           </plugin>
       </plugins>
   </build>

Save the pom.xml file.

  1. Run Maven Test: Right-click on your project in Eclipse, select Run As -> Maven Test. This will execute the TestNG tests using the Surefire Plugin configuration.

By following these alternative methods, you can achieve TestNG integration without relying on the TestNG Eclipse plugin or by executing tests directly from the command line. Choose the approach that best fits your workflow and project requirements.

Conclusion

By exploring parameterized tests, listeners, parallel execution, and data-driven testing, we’ve added advanced features to our TestNG and Maven integration. These practices enhance the capabilities of your testing suite and contribute to the overall effectiveness of your test automation efforts.

Remember to adapt these practices based on your specific project requirements and scale. As you continue to work with TestNG and Maven in Eclipse, you’ll discover additional features and configurations that suit your testing needs.

Happy Coding!

You Might Also Like

20 Demo Sites for Automation Testing

Page Object Model (POM) and Page Factory Guide in Selenium Java

Selenium 4 Relative Locators Guide

Selenium Version 4 Features – What’s New?

How to Inspect Element in Safari, Android, and iPhone

TAGGED:TestNG Examples
Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Different Ways to Loop Through a Dictionary in Python with Examples Multiple Ways to Loop Through a Dictionary in Python
Next Article Unable to install TestNG in Eclipse Unable to install TestNG in Eclipse – What to do?

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x