简体   繁体   中英

Run a TestNG test instance

I would like to run programmatically an instance of TestNG test. My test is like this:

public class MyTest {
    private Browser browser;
    private User user;

    public MyTest(Browser browser, User user) {
        this.browser = browser;
        this.user = user;
    }

    @Test public void testExample() {
        ...
    }
}

Since my test requires some objects to be passed to it's constructor to work I can't simply provide the test class object. So this won't work:

TestNG testng = new TestNG();
testng.setTestClasses(MyTest.class);
testng.run();

Any ideas on how can I do it with TestNG?

You have a couple of options:

  • Use a @Factory to create your objects.
  • Use TestNG's Guice support (the @Guice annotation) to inject the Browser and User objects.

You can actually both these approaches together.

You can use a stactic variable or method to get those objects. But that only works if you dont plan on parallel execution of your tests.

public class ExampleClass{

private static Browser browser;

public DriverContainer(Browser brows){
    browser = brows;
}

public static Browser getBrowser() {
    return browser;
}

ExampleClass could be createdin another test class in an @BeforeSuite or @BeforeTest method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM