Sunday, May 5, 2024
HomeJavaAn Introduction to TestNG Framework - Java Code Geeks

An Introduction to TestNG Framework – Java Code Geeks


TestNG is a testing framework for Java that’s extensively utilized in take a look at automation. It gives a variety of options for writing and operating exams, together with annotations, take a look at configuration, data-driven testing, parallel execution, and reporting.

Annotations are a key function of TestNG, permitting builders to specify the habits of take a look at strategies utilizing easy, descriptive key phrases comparable to @Check, @BeforeMethod, @AfterMethod, @DataProvider, and @Parameters. These annotations allow TestNG to routinely execute exams in a specified order and with a predefined set of knowledge inputs.

Check configuration is one other essential function of TestNG, permitting builders to arrange take a look at environments, initialize take a look at information, and configure take a look at settings. TestNG additionally helps data-driven testing, which permits builders to run the identical take a look at with totally different units of knowledge inputs. This function is especially helpful for testing advanced programs with a number of enter parameters.

Parallel execution is one other key function of TestNG, enabling builders to execute exams concurrently throughout a number of threads, processors, or machines. This helps to scale back the time required to run massive take a look at suites and to enhance take a look at effectivity.

TestNG additionally gives complete reporting options, permitting builders to generate detailed take a look at experiences, monitor take a look at outcomes, and determine areas for enchancment.

Total, TestNG is a robust and versatile testing framework that’s well-suited for automated testing in Java-based purposes.

1. JUnit 5 vs. TestNG

JUnit and TestNG are the preferred Java frameworks for automated Selenium testing. Under we will see their foremost variations.

Listed here are some key variations between the 2:

  1. Annotations: TestNG gives a wider vary of annotations than JUnit 5, making it simpler to arrange take a look at configurations and execute exams in a particular order.
  2. Reporting: TestNG gives higher reporting capabilities out of the field, together with HTML experiences that present the standing of every take a look at and their related information.
  3. Parallel execution: Each frameworks help parallel execution of exams, however TestNG’s parallel execution capabilities are extra superior and versatile.
  4. Extension mannequin: JUnit 5 has a extra sturdy and versatile extension mannequin, which permits builders to customise and lengthen the framework’s habits extra simply.
  5. Assertions: JUnit 5 has a extra complete set of built-in assertions, making it simpler to jot down concise and readable exams.
  6. Platform help: JUnit 5 has higher help for operating exams on totally different platforms, together with the power to run exams on the Java Digital Machine (JVM), within the browser, and on cellular gadgets.

In the end, the selection between JUnit 5 and TestNG will rely on the particular wants of the mission and the preferences of the event staff. Each frameworks are highly effective and versatile, and can be utilized to create efficient and environment friendly take a look at suites for Java purposes.

2. Getting Began With TestNG

Listed here are the steps to get began with TestNG:

  1. Set up TestNG: TestNG could be simply put in utilizing a construct instrument comparable to Maven or Gradle. To put in TestNG utilizing Maven, add the next dependency to your mission’s pom.xml file:
<dependency>
    <groupId>org.testng</groupId>
    <artifactId>testng</artifactId>
    <model>7.4.0</model>
    <scope>take a look at</scope>
</dependency>
  • Create a TestNG take a look at class: A TestNG take a look at class is a Java class that accommodates a number of take a look at strategies, annotated with the @Check annotation. Right here’s an instance:
import org.testng.annotations.Check;

public class MyTestNGTest {

    @Check
    public void testMethod() {
        // Your take a look at code right here
    }
}
  • Configure TestNG: TestNG gives a variety of configuration choices to customise the habits of your exams. Configuration could be performed utilizing XML information or programmatically utilizing Java code. Right here’s an instance of a TestNG XML configuration file:
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite title="MyTestSuite">
  <take a look at title="MyTest">
    <courses>
      <class title="com.instance.MyTestNGTest"/>
    </courses>
  </take a look at>
</suite>
  • Run your exams: After getting created your take a look at class and configured TestNG, you may run your exams utilizing your construct instrument or from the command line. To run exams from the command line, use the next command:
java -cp <path to your take a look at courses and dependencies> org.testng.TestNG <path to your testng.xml file>

For instance, in case your take a look at courses and dependencies are positioned within the “goal” listing, and your TestNG XML configuration file is positioned within the “src/take a look at/sources” listing, you may run your exams with the next command:

java -cp goal/*:goal/courses org.testng.TestNG src/take a look at/sources/testng.xml
  • Analyze take a look at outcomes: TestNG gives detailed experiences of take a look at outcomes, together with data on handed, failed, and skipped exams, in addition to the time taken to run every take a look at. The default take a look at report is an HTML file positioned within the “test-output” listing.

That’s it! With these steps, you need to be capable of get began with TestNG and create efficient and environment friendly take a look at suites to your Java purposes.

3. Strategies To Run Checks with TestNG

3.1 Automation TestNG With Selenium

Right here’s how you should use TestNG with Selenium to create automated exams:

  • Arrange your Selenium setting: Earlier than you should use TestNG with Selenium, you might want to arrange your Selenium setting. This includes downloading the mandatory WebDriver executable to your browser and including it to your system PATH. Additionally, you will want so as to add the Selenium Java bindings to your mission’s construct path. Right here’s an instance of how to do that with Maven:
<dependencies>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <model>4.1.0</model>
    </dependency>
</dependencies>
  • Create a TestNG take a look at class: A TestNG take a look at class is a Java class that accommodates a number of take a look at strategies, annotated with the @Check annotation. Right here’s an instance:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Check;

public class MySeleniumTest {

    personal WebDriver driver;

    @BeforeMethod
    public void setUp() {
        // Arrange the WebDriver occasion
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver.exe");
        driver = new ChromeDriver();
    }

    @AfterMethod
    public void tearDown() {
        // Stop the WebDriver occasion
        driver.give up();
    }

    @Check
    public void testSearch() {
        // Navigate to the Google homepage
        driver.get("https://www.google.com/");

        // Seek for TestNG
        driver.findElement(By.title("q")).sendKeys("TestNG");
        driver.findElement(By.title("btnK")).click on();

        // Confirm that the search outcomes web page title accommodates "TestNG"
        String title = driver.getTitle();
        Assert.assertTrue(title.accommodates("TestNG"));
    }
}
  • Run your exams: After getting created your take a look at class, you may run your exams utilizing TestNG as described within the earlier reply.
  • Analyze take a look at outcomes: TestNG gives detailed experiences of take a look at outcomes, together with data on handed, failed, and skipped exams, in addition to the time taken to run every take a look at. The default take a look at report is an HTML file positioned within the “test-output” listing.

That’s it! With these steps, you need to be capable of use TestNG with Selenium to create automated exams to your internet purposes. You should utilize Selenium’s numerous APIs to work together with internet parts and carry out actions, and TestNG’s annotations to regulate the move of your exams.

3.2 Parallel Check Execution in TestNG

TestNG gives a robust function to execute exams in parallel, which may significantly cut back the time required to run a big suite of exams. Right here’s how one can execute exams in parallel with TestNG:

  1. Configure parallel execution: TestNG gives a number of choices for parallel execution, which could be configured within the TestNG XML configuration file. The choices embrace:
    • parallel: This attribute specifies the kind of parallel execution. The doable values are “strategies”, “exams”, “courses”, “situations”, or “none”. For instance, to execute all strategies in parallel, set parallel="strategies" within the take a look at tag.
    • thread-count: This attribute specifies the variety of threads to make use of for parallel execution. For instance, to make use of 5 threads, set thread-count="5" within the take a look at tag.

Right here’s an instance of a TestNG XML configuration file that runs exams in parallel:

<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite title="MyTestSuite" parallel="strategies" thread-count="5">
  <take a look at title="MyTest">
    <courses>
      <class title="com.instance.MyTestNGTest"/>
    </courses>
  </take a look at>
</suite>
  • Annotate take a look at strategies: So as to run take a look at strategies in parallel, annotate them with the @Check annotation and set the threadPoolSize attribute to the variety of threads you need to use. For instance:
import org.testng.annotations.Check;

public class MyTestNGTest {

    @Check(threadPoolSize = 5, invocationCount = 10)
    public void testMethod() {
        // Your take a look at code right here
    }
}

It will run the testMethod() 10 occasions, with 5 threads operating in parallel.

  • Run your exams: After getting configured your parallel execution and annotated your take a look at strategies, you may run your exams as traditional utilizing TestNG.

TestNG additionally gives different options to customise the parallel execution of your exams, comparable to thread security, thread timeouts, and extra. With these options, you may create environment friendly and efficient take a look at suites that may run in parallel to avoid wasting time and improve productiveness.

3.3 Creating TestNG XML File

To create a TestNG XML file, you have to to specify the configuration to your take a look at suite, together with the courses, strategies, and parameters to be executed. Right here’s a step-by-step information to making a TestNG XML file:

  • Create a brand new XML file: In your mission, create a brand new file with the extension .xml. This file will include the TestNG configuration to your take a look at suite.
  • Outline the XML construction: The TestNG XML file ought to begin with an XML declaration, adopted by a <!DOCTYPE> declaration that factors to the TestNG DTD, and a root <!DOCTYPE> aspect named suite. Right here’s an instance:
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite title="MyTestSuite">
  <!-- Configuration goes right here -->
</suite>
  • Outline take a look at configuration: Throughout the suite aspect, you may outline a number of take a look at parts, every representing a set of exams to be executed. The take a look at aspect can have a title attribute and will include a number of class parts, every representing a Java class to be examined. Right here’s an instance:
<suite title="MyTestSuite">
  <take a look at title="MyTest">
    <courses>
      <class title="com.instance.MyTestClass"/>
    </courses>
  </take a look at>
</suite>
  • Outline take a look at methodology configuration: Throughout the class aspect, you may outline a number of test-method parts, every representing a take a look at methodology to be executed. The test-method aspect can have a title attribute, in addition to non-compulsory attributes comparable to enabled, description, teams, and depends-on-method. Right here’s an instance:
<suite title="MyTestSuite">
  <take a look at title="MyTest">
    <courses>
      <class title="com.instance.MyTestClass">
        <strategies>
          <embrace title="testMethod1" />
          <embrace title="testMethod2" />
          <exclude title="testMethod3" />
        </strategies>
      </class>
    </courses>
  </take a look at>
</suite>

On this instance, we have now included testMethod1 and testMethod2, and excluded testMethod3.

  • Outline parameters: You may as well outline parameters in your TestNG XML file, which can be utilized to configure your exams. Parameters could be outlined on the suite, take a look at, class, or methodology stage, and could be referenced in your take a look at code utilizing the @Parameters annotation. Right here’s an instance:
<suite title="MyTestSuite">
  <parameter title="baseUrl" worth="https://www.google.com" />
  <take a look at title="MyTest">
    <parameter title="searchTerm" worth="TestNG" />
    <courses>
      <class title="com.instance.MyTestClass" />
    </courses>
  </take a look at>
</suite>

On this instance, we have now outlined a parameter named baseUrl on the suite stage, and a parameter named searchTerm on the take a look at stage.

  • Save the XML file: After getting outlined your TestNG XML configuration, save the file with a descriptive title, comparable to testng.xml.

That’s it! Now you can use this TestNG XML file to run your exams. To execute the exams outlined within the XML file, you should use the TestNG command-line instrument or your most popular construct instrument, comparable to Maven or Gradle.

3.4 Automation With Selenium, Cucumber, and TestNG

Selenium, Cucumber, and TestNG can be utilized collectively for automated testing of internet purposes. Right here’s how one can arrange and use these instruments collectively:

  • Set up Selenium WebDriver: Begin by putting in Selenium WebDriver to your most popular programming language. WebDriver is the core part of Selenium that gives a library for interacting with internet browsers. You may set up it utilizing a bundle supervisor or by downloading it from the Selenium web site.
  • Set up Cucumber: Subsequent, set up Cucumber to your programming language. Cucumber is a behavior-driven improvement (BDD) framework that means that you can write executable specs in plain textual content. You may set up it utilizing a bundle supervisor or by downloading it from the Cucumber web site.
  • Set up TestNG: Lastly, set up TestNG to your programming language. TestNG is a testing framework that gives superior options comparable to parallel testing, data-driven testing, and take a look at configuration by XML information. You may set up it utilizing a bundle supervisor or by downloading it from the TestNG web site.
  • Create a Cucumber function file: Begin by making a function file within the options listing of your mission. This file will include the eventualities to your take a look at suite, written in Gherkin syntax. Right here’s an instance:
Characteristic: Search on Google
  As a consumer
  I need to seek for a time period on Google
  In order that I can discover data

  Situation: Looking for TestNG on Google
    Given I'm on the Google search web page
    After I enter "TestNG" within the search field
    And I click on the search button
    Then I ought to see search outcomes for "TestNG"
  • Create a step definition file: Subsequent, create a step definition file within the step_definitions listing of your mission. This file will include the code that maps the steps within the function file to precise Selenium WebDriver instructions. Right here’s an instance:
public class SearchSteps {
  personal WebDriver driver;
  
  @Given("^I'm on the Google search web page$")
  public void i_am_on_the_google_search_page() {
    driver = new ChromeDriver();
    driver.get("https://www.google.com/");
  }
  
  @When("^I enter "(.*)" within the search field$")
  public void i_enter_search_term(String searchTerm) {
    WebElement searchBox = driver.findElement(By.title("q"));
    searchBox.sendKeys(searchTerm);
  }
  
  @When("^I click on the search button$")
  public void i_click_the_search_button() {
    WebElement searchButton = driver.findElement(By.title("btnK"));
    searchButton.click on();
  }
  
  @Then("^I ought to see search outcomes for "(.*)"$")
  public void i_should_see_search_results(String searchTerm) {
    WebElement resultsStats = driver.findElement(By.id("result-stats"));
    assertThat(resultsStats.getText()).accommodates(searchTerm);
    driver.give up();
  }
}
  • Create a TestNG XML file: Lastly, create a TestNG XML file within the root listing of your mission. This file will specify the configuration to your take a look at suite, together with the Cucumber function file and the TestNG take a look at class. Right here’s an instance:
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite title="MyTestSuite">
  <take a look at title="MyTest">
    <courses>
      <class title="cucumber.api.testng.CucumberTestNGRunner">
        <strategies>
          <embrace title=".*" />
        </strategies>
        <params>
          <param title="cucumber.options" worth="src/take a look at/sources/options" />
          <param title="cucumber.glue" worth="step_definitions" />
        </params>
      </class
    </courses>
  </take a look at>
</suite>

3.5 Run JUnit Selenium Checks Utilizing TestNG

JUnit and TestNG are each in style testing frameworks for Java. Whereas JUnit is targeted on unit testing, TestNG gives options for integration and practical testing as effectively. In case you have current Selenium exams written with JUnit and also you need to run them utilizing TestNG, you may comply with these steps:

  • Set up TestNG: Set up TestNG in your improvement setting. You may set up it utilizing a bundle supervisor or by downloading it from the TestNG web site.
  • Create a TestNG XML file: Create a TestNG XML file that specifies the configuration to your take a look at suite. Right here’s an instance:
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite title="MyTestSuite">
  <take a look at title="MyTest">
    <courses>
      <class title="com.instance.exams.LoginTest"/>
    </courses>
  </take a look at>
</suite>

This file defines a take a look at suite named MyTestSuite with a single take a look at named MyTest. The take a look at features a single class named com.instance.exams.LoginTest.

  • Convert JUnit exams to TestNG: To transform JUnit exams to TestNG, you may merely add @Check annotations to your current take a look at strategies. Right here’s an instance:
public class LoginTest {
  personal WebDriver driver;

  @Earlier than
  public void setUp() {
    driver = new ChromeDriver();
  }

  @After
  public void tearDown() {
    driver.give up();
  }

  @Check
  public void testLogin() {
    driver.get("http://www.instance.com/login");
    WebElement usernameField = driver.findElement(By.title("username"));
    WebElement passwordField = driver.findElement(By.title("password"));
    WebElement loginButton = driver.findElement(By.title("login"));

    usernameField.sendKeys("myusername");
    passwordField.sendKeys("mypassword");
    loginButton.click on();

    assertTrue(driver.getTitle().accommodates("Dashboard"));
  }
}

On this instance, the @Check annotation has been added to the testLogin() methodology.

  • Run the exams: Run the exams utilizing the TestNG XML file. You are able to do this utilizing the TestNG command-line instrument, or by configuring your construct system to run the exams utilizing TestNG. Right here’s an instance of operating the exams utilizing the TestNG command-line instrument:
$ java -cp testng.jar:mytests.jar org.testng.TestNG testng.xml

This command runs the exams outlined in mytests.jar utilizing the configuration laid out in testng.xml.

4. Use Circumstances for TestNG

TestNG is a well-liked testing framework for Java that gives a variety of options to assist builders and testers write sturdy and environment friendly exams. Listed here are some use instances for TestNG:

  1. Unit testing: TestNG is usually used for unit testing as a result of it permits builders to jot down exams which might be simple to keep up, execute rapidly, and report on the outcomes. TestNG gives annotations, comparable to @Check, @BeforeMethod, and @AfterMethod, that make it simple to jot down and manage unit exams.
  2. Integration testing: TestNG may also be used for integration testing, the place a number of elements of an software are examined collectively to make sure that they work appropriately. TestNG’s help for teams, dependencies, and information suppliers make it simple to jot down and execute integration exams.
  3. Parameterized testing: TestNG gives help for parameterized testing, which permits builders to jot down a single take a look at methodology that may be executed with a number of units of take a look at information. This makes it simple to check a variety of eventualities with minimal code duplication.
  4. Knowledge-driven testing: TestNG additionally gives help for data-driven testing, the place take a look at information is saved individually from the take a look at code. This makes it simple to change and reuse take a look at information with out altering the take a look at code.
  5. Parallel testing: TestNG permits exams to be run in parallel, which may significantly cut back the time it takes to execute a big suite of exams. TestNG can run exams in parallel on the methodology, class, take a look at, and suite ranges.
  6. Check configuration and administration: TestNG permits builders to configure and handle exams simply. TestNG gives a complete XML configuration file that can be utilized to specify the take a look at suite, take a look at strategies, take a look at information, take a look at teams, and extra. Moreover, TestNG helps numerous listeners and reporters that can be utilized to customise the take a look at execution and generate detailed experiences.

In abstract, TestNG is a flexible and highly effective testing framework that can be utilized for a variety of testing eventualities, from unit testing to integration testing, parameterized testing, data-driven testing, and extra.

5. Conclusion

In conclusion, TestNG is a extremely helpful and in style testing framework for Java that gives a variety of options to assist builders and testers write sturdy and environment friendly exams. It presents help for unit testing, integration testing, parameterized testing, data-driven testing, and parallel testing, in addition to complete take a look at configuration and administration choices. With TestNG, builders can simply write, manage, and execute exams, whereas producing detailed experiences to assist determine and repair points rapidly. Total, TestNG is a vital instrument for any Java developer trying to construct high-quality software program with dependable and efficient exams.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments