Writing first test case

In this chapter, we will guide you through the process of writing test cases using TestNG, from setting up your project to creating and executing test methods.

In the Environment Setup chapter we have seen the process of creating project using maven for testng. You can use the same project or follow the same process to create new project. We will follow the same project for rest of our chapters.
Let's crate a new class called AppTest2.java and update the file with following code.
Java
Copy
import org.testng.annotations.Test;
    
    public class AppTest2 
    {
        @Test
        public void method1()
        {
            System.out.println("This is method 1");
        }
    }
    
To run the test follow below steps:
  1. Right click on the file in your editor
  2. Click on Run or Run as TestNG Test
The above code contains simple test case which will print the text 'method1'.
Now add two more methods eg. method2 and method3 and try to run the test. You won't see anything new but two more output. These three methods will be your test cases that in real time will perform testing of different functionalities.

@Before Method and @After Method

Now let's add @BeforeMethod and @AfterMethod annotations and see what are the changes. Update your file with below code.
Java
Copy
import org.testng.annotations.AfterMethod;
    import org.testng.annotations.BeforeMethod;
    import org.testng.annotations.Test;
    
    public class AppTest2 
    {
        @BeforeMethod
        public void beforeMethodFunc()
        {
            System.out.println("Before Method");
        }
        @AfterMethod
        public void afterMethodFunc()
        {
            System.out.println("After Method");
        }
        @Test
        public void method1()
        {
            System.out.println("This is method 1");
        }
        @Test
        public void method2()
        {
            System.out.println("This is method 2");
        }
        @Test
        public void method3()
        {
            System.out.println("This is method 3");
        }
    }
    
Now run the test and see the difference. You may see the method with @BeforeMethod annotation is executed before all the methods with @Test annotations and method with @AfterMethod annotation is executed after all the methods with @Test annotation.

This indicates that these annotations have the ability to modify or add some pre and post alterations to the resources of your test eg. Loading test data for test case, Performing pre-requisite, cleaning the database etc. The functionality will remain the same for other before and after annotations.

Try adding other before and after annotations and run the test and see what are your findings. We will learn more about these annotation in coming chapters.