4🧪 Unit Test

TestNG

1. Prerequisites

  • Java Development Kit (JDK) 21 installed.

  • Apache Maven installed.

  • An IDE (IntelliJ IDEA, Eclipse, or VS Code).

2. Create a Maven Project

You can create a new Maven project using your IDE or via the command line:

mvn archetype:generate -DgroupId=com.example -DartifactId=testng-demo -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

3. Configure pom.xml

Open pom.xml and add the TestNG dependency. Ensure the compiler source and target are set to 21.

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>testng-demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>21</maven.compiler.source>
        <maven.compiler.target>21</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <!-- TestNG Dependency -->
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>7.10.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

4. Create a Class to Test

Create a simple Calculator class in src/main/java/com/example/Calculator.java.

5. Write a TestNG Test

Create a test class in src/test/java/com/example/CalculatorTest.java.

6. Run the Tests

You can run the tests using the Maven command:

Jest

1. Prerequisites

  • Node.js installed (includes npm).

  • An IDE (VS Code recommended).

2. Initialize a Node.js Project

Create a new folder for your project and initialize it:

3. Install Jest

Install Jest as a development dependency:

4. Configure package.json

Open package.json and change the test script to run jest:

5. Create a Function to Test

Create a file named sum.js:

6. Write a Jest Test

Create a file named sum.test.js:

7. Run the Tests

Run the following command in your terminal:

Last updated