0

I have one scenario where i would have only one test method in my testNG test class and i have to form multiple tests from it the reason i'm writting only one test method is that i don't know how many tests i would need, because that number depends on the number of URL's which i'm fetching from a excel sheet.

So basically i will have only one testNG test method which will fetch different URL from excel each time and execute the test and according to test result my listener will mark the test as pass or fail. Say for example i have 20 URL's in my excel sheet so can one testNG test method execute these 20 URL's one by one and give pass/fail results 20 times. Means at the end i should see 20 tests executed with there pass/fail results. How can i achieve this ?

Vaibhav
  • 29
  • 4

1 Answers1

0

Basically You would like to run your test with different data sets,

To do so, you may implement a @Factory annotated constructor and tie this constructor's @Factory annotation to a @DataProvider annotated data provider method

In addition you may use Apache POI to fetch the urls from the given excel file.

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

import static org.testng.Assert.assertNotNull;

public class SampleTest {

  private final String url;

  @Factory(dataProvider = "getUrls")
  public SampleTest(String url) {
    this.url = url;
  }

  @DataProvider(name = "getUrls")
  public static Iterator<Object[]> loadUrls() throws IOException {
    InputStream inputStream =
        SampleTest.class.getClassLoader().getResourceAsStream("urls-sheet.xlsx");

    try (Workbook workbook = new XSSFWorkbook(inputStream)) {
      Iterable<Row> iterable = () -> workbook.getSheetAt(0).iterator();
      Stream<Row> rows = StreamSupport.stream(iterable.spliterator(), false);

      return rows.map(row -> new Object[] {row.getCell(0).getStringCellValue()}).iterator();
    }
  }

  @Test
  public void testProvidedUrl() {
    assertNotNull(url, "url should have a value");
  }
}

Demo source code

See

TestNG @DataProvider – Test parameters example

How to run multiple test cases in testng with different set of test data from excel file?

eHayik
  • 2,981
  • 1
  • 21
  • 33
  • thank you :). One more question i will be not knowing how many url's are there its dynamic, so how should i handle the data provider. – Vaibhav Jan 28 '21 at 10:31
  • You may use Apache POI library to fetch the urls from the excel file within your data provider method, I will update my answer to show you how – eHayik Jan 28 '21 at 13:13