Once you learn TestNG, you will master half of Java unit testing!

01, TestNG

01. Introduction

In daily testing work, it is often necessary to write codes and scripts to complete some testing tasks, such as automated testing, interface testing, unit testing, etc. After writing a number of scripts, these scripts need to be organized, managed and the results collected. At this time, a tool is needed to take charge of these things, so TestNG appeared.

TestNGis a testing framework in the Java system, which can be used for unit testing, integration testing, etc. Before TestNG, a similar framework had appeared long ago, and that was Junit. TestNG borrows some features from Junit and then adds many more powerful functions. It has become the most widely used testing framework in the Java system.

It should be noted that many people understand that TestNG is an interface testing framework, but in fact it is not. TestNG itself cannot do interface testing. It is mainly used to manage your interface testing. Similar to the pytest framework in Python. Today we will introduce the use of TestNG in detail.

02. Environment installation

Create a Maven project and introduce TestNG dependency packages

<dependency>

   <groupId>org.testng</groupId>
   <artifactId>testng</artifactId>

   <version>6.8</version>

</dependency>

A simple example

Write a simple calculator class

//A simple addition, subtraction, multiplication and division calculator
public class Calculator {
    // addition
    public int add(int a, int b){
        return a + b;
    }
    // subtraction
    public int subtract(int a, int b){
        return a - b;
    }
    //Multiplication
    public int multiply(int a, int b){
        return a * b;
    }
    // division
    public int divide(int a, int b){
        return a / b;
    }
}

Next, unit test the calculator, create a test class, and write a test method for the addition operation.

// Calculator test class
public class CalculatorTest {
    //Addition test
    @Test
    public void testAdd(){
        System.out.println("Start executing testAdd");
        Calculator calculator = new Calculator();
        int result = calculator.add(1, 1);
        Assert.assertEquals(2, result);
    }
    // subtraction test
    @Test
    public void testSubtract(){
        System.out.println("Start executing testSubtract");
        Calculator calculator = new Calculator();
        int result = calculator.subtract(2, 1);
        Assert.assertEquals(1, result);
    }
}

Note:

  • In the above code, a @Test annotation is added to the testAdd method. This is an annotation provided by TestNG (can be understood as a mark). The changed annotation indicates that this method requires TestNG to execute. The @Test annotation is also the most commonly used annotation.
  • Assert is the assertion class in TestNG, and assertEquals is the most commonly used method, used to determine whether the expected value and the actual value are consistent. If they are consistent, the test passes; if they are inconsistent, the test fails.
Now I have also found a lot of test friends and created a communication group to share technology, sharing a lot of technical documents and video tutorials we collected.
If you don’t want to experience the feeling of not being able to find resources when studying on your own, having no one to answer your questions, and persisting for a few days before giving up.
You can join us to communicate. And there are many technical experts who have made certain achievements in automation, performance, security, test development, etc.
Share their experience, and also share many live lectures and technical salons
You can learn for free! Focus on it! Open source! ! !
QQ group number: 110685036

03. TestNG execution

IntelliJ IDEA has built-in TestNG support, so just right-click on the method name and select “run testAdd”, and the execution results of the use case will be printed on the console.

If the console prints everything in green, it means the execution was successful.

You can also right-click on the class and run it. TestNG will run all the test methods annotated with @Test in the entire class.

02, Suite Test

01. Kit definition

Several test methods will be written in a test class. If a scenario requires the execution of multiple test classes, suite testing is required. A suite is a collection of test classes. In TestNG, you need to use an xml file to define a suite, which can contain one or more test classes. There are also many flexible configurations in xml to achieve some refined execution strategies.

Create a testng.xml in the resource directory of the Maven project

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="TestAll">
  <!--Execute the entire class-->
    <test name="calculator_all_class">
        <classes>
             <!-- Specify the class name, you can add multiple -->
            <class name="com.mtx.CalculatorTest"></class>
        </classes>
    </test>
    <!--Only execute a certain method-->
    <test name="calculator_one_method">
        <classes>
            <class name="com.mtx.CalculatorTest">
                <methods>
                       <!--Specify the method name, you can add multiple -->
                    <include name="testAdd"></include>
                </methods>
            </class>
        </classes>
    </test>
</suite>

In xml, a test tag represents an execution case, which can execute one or more classes, or specify one or more methods (see comments)

02. Suite execution

Right-click run on xml to run the entire suite and the execution results

03. Data driven

In many test cases, for the same set of logic, a large amount of different data needs to be used for verification. In this case, you can use TestNG’s @DataProvider annotation to provide data and drive the execution of the test case.

Define a data-driven method in the test class and add the @DataProvider annotation

// Addition test
@Test(dataProvider = "testAddData")
public void testAdd(int a, int b, int expect){
    System.out.println("Start executing testAdd");
    Calculator calculator = new Calculator();
    int result = calculator.add(a, b);
    Assert.assertEquals(expect, result);
}
// Three sets of test data are provided: {number 1, number 2, expected value}
// Because the return type is Object, other data types can also be written in the array, such as String, int, char, float, etc.
@DataProvider(name = "testAddData")
public Object[][] testAddData(){
    Object[][] data = new Object[][]{<!-- -->{1, 1, 2}, {2, 2, 4}, {3, 3, 5}};
    return data;
}

Note:

  • The providerData method that provides data must be annotated @DataProvider, and the execution name is testAddData. The data type returned by the method must be Object two-dimensional array
  • In the testAdd method that uses data, the corresponding dataprovider name must be specified, and the corresponding number and type of input parameters must be defined on the method to accept data.

After executing the testAdd method, it was found that it was executed three times, with different parameters passed in each time. The third set of data was executed because the actual and expected data were inconsistent, and the execution result was a failure.

04. Other notes

In addition to the @Test annotation, there are some other annotations that are also commonly used, as follows:

< /table>

@BeforeSuite
public void suiteInit(){
    System.out.println("Test before suite execution");
}
@AfterSuite
public void suiteEnd(){
    System.out.println("Test after suite execution");
}
@BeforeClass
public void classInit(){
    System.out.println("Test before class execution");
}
@AfterClass
public void classEnd(){
    System.out.println("Test after class execution");
}
@BeforeTest
public void testInit(){
    System.out.println("Test before test method execution");
}
@AfterTest
public void testEnd(){
    System.out.println("Test after test method execution");
}

Execution results:

05. Command line execution

In addition to executing the TestNG test method in idea, another more practical execution method is command line execution. Using command line execution is easier to integrate with other external tools, Such as Jenkins. However, the command line execution method provided by TestNG itself is not easy to use. The simpler method is to integrate with Maven and use the maven method to call TestNG.

In the project pom file, add the plug-in:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <configuration>
                <testFailureIgnore>true</testFailureIgnore>
                <suiteXmlFiles>
                    <suiteXmlFile>src/main/resources/testng.xml</suiteXmlFile>
                </suiteXmlFiles>
            </configuration>
        </plugin>
    </plugins>
</build>

In the suiteXmlFile tag, specify the relative location of the testng.xml file.

Then under cmd, enter the project directory and execute the command: mvn test. You can see that the test results are finally printed in the console.

Finally, I would like to thank everyone who has read my article carefully. Looking at the increase in fans and attention, there is always some courtesy. Although it is not a very valuable thing, if you can use it, you can take it directly!

Software testing interview documents

We must study to find a high-paying job. The following interview questions are the latest interview materials from first-tier Internet companies such as Alibaba, Tencent, Byte, etc., and some Byte bosses have given authoritative answers. After finishing this set I believe everyone can find a satisfactory job based on the interview information.

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Java Skill TreeHomepageOverview 137397 people are learning the system

syntaxbug.com © 2021 All Rights Reserved.
Annotations Description
@BeforeSuite Executed before suite tests are executed , run only once
@AfterSuite Executed after the suite test is executed, run only once
@BeforeClass Execute before the entire test class is executed, only run once
@AfterClass After the entire test class is executed Execute, only run once
@BeforeTest Executed before the @Test annotated method is executed, each @Test method is executed once
@AfterTest Executed after the @Test annotated method is executed, each @Test method is executed once