Search code examples
javaselenium-webdrivertestngtestng-dataprovider

TestNG: Specific data from DataProvider for specific test methods


Is it possible to specify data from DataProvider for each test method. I've made something like this.

@DataProvider(name = "loginData")
public Object[][] getData(Method m) {
    if (m.getName().equalsIgnoreCase("testValidLogin")) {
        return new Object[][]{
                {"aaa", "qwe123!"}
        };
    }
    if (m.getName().equalsIgnoreCase("testSendMail")){
            return new Object[][]{
                    {"Test@test", "Test", "Hi there!"}
            };
    } else {
        return new Object[][]{
                {"12312312","123qwe"},
        };
   }
}`

Is there better way to do this? Can I specify one data set for two test methods? Thanks!


Solution

  • If your test data is test method related it better keep it in the test method or create separate data provider.

    Additional option is to use test context and pass required parameters through it from before methods to test method.

    Or you can build something like that:

    public class DataProviderPerMethod {
    
        @DataProvider(name = "provider")
        public Object[][] provider(Method method) {
            List<TestData> options = Arrays.asList(method.getAnnotation(TestDataOptions.class).value());
            int optionsSize = options.size();
            int optionLength = Objects.requireNonNull(options.get(0)).value().length;
            Object[][] result = new Object[optionsSize][optionLength];
            IntStream.range(0, optionsSize).forEach(i -> result[i] = options.get(i).value());
            return result;
        }
    
        @Retention(RetentionPolicy.RUNTIME)
        @Target(ElementType.METHOD)
        @Repeatable(TestDataOptions.class)
        public @interface TestData {
            String[] value();
        }
    
        @Retention(RetentionPolicy.RUNTIME)
        @Target(ElementType.METHOD)
        public @interface TestDataOptions {
            TestData[] value();
        }
    
    
        @TestDataOptions({
                @TestData({"1", "string"}),
                @TestData({"2", "else one string"})
        })
        @Test(dataProvider = "provider")
        public void verifyTestData(String first, String second) {
            System.out.println(first);
            System.out.println(second);
        }
    
    }