milosdju
milosdju

Reputation: 803

Can I manage @DataProvider to run after @BeforeMethod

Above my @Test method I have annotation which contains name of file from which @DataProvider should pull data. I tried initializing that File in @BeforeMethod but I haven't succeeded cause @BeforeMethod runs AFTER @DataProvider.

Reason why I need to initialize File in @BeforeMethod is that I can only from that method know which @Test method is run and then pull its annotation with file name. Also, I want do it before every @Test method run. How I can make this thing works?

String fileName;

@MyAnnotation(fileName="abc.txt")
@Test(dataProvider = "getData")
public void test(DataFromFile data) {
    ...showData();
}

@BeforeMethod
public void beforeMethod(Method invokingMethod) {
    fileName ... = invokingMethod.getAnnotation(MyAnnotation.class).fileName();
}

@DataProvider
public Object[][] getData() { 
    ... initialize new File(fileName);
    ... 
}

Upvotes: 1

Views: 1395

Answers (1)

Krishnan Mahadevan
Krishnan Mahadevan

Reputation: 14736

You should perhaps do something like this

package com.rationaleemotions.stackoverflow;

import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.reflect.Method;

import static java.lang.annotation.ElementType.METHOD;

public class DataProviderGames {
    @Test(dataProvider = "getData")
    @MyAnnotation(fileName = "input.txt")
    public void test(String data) {
        System.err.println("Test data :" + data);
    }

    @Test(dataProvider = "getData")
    @MyAnnotation(fileName = "input.csv")
    public void anotherTest(String data) {
        System.err.println("Test data :" + data);
    }

    @DataProvider
    public Object[][] getData(Method method) {
        MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
        return new Object[][]{
                {annotation.fileName()}
        };
    }

    @Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
    @Target({METHOD})
    @interface MyAnnotation {
        String fileName() default "";
    }
}

Since TestNG gives you the provision of injecting the actual "Method" for which the @DataProvider annotated method is being called, you should be directly able to use reflection to query the Method parameter for its annotations and retrieve the file name via it.

Upvotes: 1

Related Questions