How does all annotations work in TestNg without ma

2019-03-31 03:38发布

问题:

I have a doubt in TestNG with Java. I am completly new to TestNG. My doubt is, How all the test cases are executing using TestNG in java without having main() method? Please suggest me if you have any ideas. Following code is the example of a sample test case using TestNG in java. But if you notice, you can find one thing that there is no main() method in the code. Then, how does the testcases are executing?

I have another doubt. Is main() method needed for selenium Webdriver and TestNG combination to execute a script? Or can we execute testcases without main() method? If we can execute testcases without main(), then how does it is possible?

package com.first.example;
import org.testng.annotations.Test;
public class demoOne {
    @Test
    public void firstTestCase()
    {
        System.out.println("im in first test case from demoOne Class");
    }

    @Test
    public void secondTestCase()
    {
        System.out.println("im in second test case from demoOne Class");
    }
}

回答1:

This is a valid doubt many testers have. Because the main() method is needed to run the Java program and while writing tests in TestNg we don't use main() method, and we use Annotations instead.

Annotations in TestNG are lines of code that can control how the method below them will be executed. So, in short you don't need to write main() method, TestNg do that by itself. Refer the code at the end in Annotations documentation to get the idea how it happens.

As rightly pointed out in this answer: https://stackoverflow.com/a/1918154/3619412

Annotations are meta-meta-objects which can be used to describe other meta-objects. Meta-objects are classes, fields and methods. Asking an object for its meta-object (e.g. anObj.getClass() ) is called introspection. The introspection can go further and we can ask a meta-object what are its annotations (e.g. aClass.getAnnotations). Introspection and annotations belong to what is called reflection and meta-programming.

Also, it's not necessary to have main() method in your tests, but you can use main() method to run the TestNg tests if you want. Refer this.



回答2:

to run script from cmd prompt we use below statement,

java org.testng.TestNG testng1.xml

main method in TestNG.java class how accept the command line argument,

 public static void main(String[] argv) {
    TestNG testng = privateMain(argv, null);
    System.exit(testng.getStatus());
  }