I’ve developed several individual test scripts in Selenium, but I’m struggling to run them all at once in a specific order. I know that TestNG allows you to group these into a "Test Suite," but I'm not sure how to structure the testng.xml file to include multiple classes or packages. Is there a way to manage parallel execution and prioritize certain test cases within the same suite file to ensure the most critical features are tested first?
3 answers
To run multiple test cases, you need to create a testng.xml file in your project root. This XML file acts as a controller for your execution. You wrap everything in a <suite> tag, and inside that, you define <test> tags. Within a <test>, you use the <classes> tag to list all the Java classes you want to execute. For example, <class name="com.project.tests.LoginTest" />. If you want to prioritize, you can add the priority attribute directly in your @Test annotations in Java. For parallel execution, simply add parallel="tests" and thread-count="5" to the <suite> tag. This allows Selenium to trigger multiple browser instances simultaneously, significantly reducing your total regression testing time.
Does using a TestNG suite allow me to share a single WebDriver instance across multiple classes, or will the XML configuration force each class to launch its own browser window? I’m worried about resource consumption if I have 20 classes running at once.
The easiest way is to right-click your project in Eclipse or IntelliJ and select "Convert to TestNG." It generates a basic testng.xml for you that you can then customize with your specific class names.
I agree with Megan. That auto-generation tool is a lifesaver for beginners. Once the file is generated, you can easily add
Justin, by default, TestNG will launch what your code tells it to. If you put your WebDriver initialization in a @BeforeMethod in a BaseClass that everyone inherits from, it will open a new window for every test. However, you can use @BeforeTest or @BeforeSuite to initialize a single driver. Be careful with parallel execution though; if multiple tests try to use the same driver instance simultaneously, they will clash. For parallel runs, it's best to use ThreadLocal to ensure each thread has its own isolated driver instance while still utilizing the suite for organization.