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.


Table of Contents

Author: Amod Mahajan

A software Tester who is paid to judge products developed by others. Writing technical posts and creating YouTube videos are my hobbies.

9 thoughts on “TestNG Tutorials 17: Can @Test Annotation Be Used For A Class In TestNG?

  1. package com.testNG;

    import org.testng.annotations.Test;

    public class TestNGannotationUpperclass {

    void m1(){
    void m2(){

    void m3(){
    void m4(){

    its not working its are showing error:

    [RemoteTestNG] detected TestNG version 6.14.2

    Default test
    Tests run: 0, Failures: 0, Skips: 0

    Default suite
    Total tests run: 0, Failures: 0, Skips: 0

    [TestNG] No tests found. Nothing was run
    Usage: [options] The XML suite files to run
    Configuration failure policy (skip or continue)
    Output directory
    Number of threads to use when running data providers
    Comma-separated list of group names to exclude
    Comma-separated list of group names to be run
    JUnit mode
    Default: false
    List of .class files or list of class names implementing ITestListener
    or ISuiteListener
    Comma separated of test methods
    Default: []

    1. Hello,
      Provide public access specifier to test methods. If methods are not public, testng can not run as methods visibility is not there.

Leave a Reply

Please wait...

Subscribe to new posts to become automation expert

Want to be notified when my new post is published? Get my posts in your inbox.