TestNG Tutorials 17: Can @Test Annotation Be Used For A Class In TestNG?

Hello Folks,

Let’s learn something new today. We have used @Test annotation on methods. Can we use @Test annotation on a class?

Yes, We can use @Test annotation on class.

Suppose, you need to write 10 @Test annotated method in a class.  Either you mark all methods as @Test annotated or directly annotate class itself as @Test.  All method will be treated as @Test annotated method by default. See an example below:

TestNG class:

Run as a testng suite:


What will happen if I need to write other annotated method like BeforeMethod or AfterMethod? Not a big deal. Mark required annotation on method. It will override class level @Test annotation. Example is as below:

TestNG class:


You can see Tests run count is 2. It means @Test annotation applied only for method without any annotation.


Another scenario: Suppose you have a class which is @Test annotated at class level. You have a sub class extending super class. Sub class is not @Test annotated method. Because of inheritance, automatically sub class will also become @Test annotated. Confused?? See below example:

Run it. You will get below output:

Liked the post? If yes please share and let others also learn.

More about TestNG in upcoming posts. Stay tuned.

If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe.


Author: Amod Mahajan

My name is Amod Mahajan and I am an IT employee with 6+ years of experience in Software testing and staying in Bengaluru. My area of interest is Automation testing. I started from basics and went through so many selenium tutorials. Thanks to Mukesh Otwani as his tutorials are easy and cover basics to advance. I have habit of exploring concepts by deep diving. I used to make notes. I thought of sharing my knowledge through posts and now I am here. #KeepLearning #ShareLearning