'How to use spring autowiring in a testng factory class
Currently I have a factory class that looks like this:
@ContextConfiguration(classes = BeanConfig.class)
public class FactoryClass extends AbstractTestNGSpringContextTests {
@Autowired
public Bean bean;
@Factory(dataProvider="dataProvider")
public Object[] createTest(int a, int b) {
return new Object[]{new FactoryTestClass(a, b)};
}
@DataProvider(name="dataProvider",parallel=true)
public Object[][] passInts(){
bean.method();
return new Object[][]{{2,2},{2,3},{2,4},{2,4}};
}
@BeforeSuite
public void beforeSuite(){
System.out.println("before suite");
}
}
My goal is to use spring's autowiring feature so i can use a bean to help generate some test data for the data provider. However in my attempt the spring context never initialises. Does anyone know what I might be doing wrong, or is there another approach I can take?
Thank you kindly, Jason
Solution 1:[1]
I had some similar issue: my test folder was located outside directory main, so, after I marked it as the Test Source Resource (in Intellij IDE) it started to work. Hope it helps.
Solution 2:[2]
Try to add loader=AnnotationConfigContextLoader.class to ContextConfiguration.
Solution 3:[3]
I would suggest to locate @DataProvider is same class as @Test method. I never had a problem with this approach.
Having various @Test methods and various dataProviders in one test class is valid usage. @Test method will specify which dataProvider is used in @Test annotation parameter.
Example:
@DataProvider(name="dataProvider",parallel=true)
public Object[][] passInts(){
bean.method();
return new Object[][]{{2,2},{2,3},{2,4},{2,4}};
}
@Test(dataProvier="dataProvider")
public test(int param1, int param2){
//...
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Igor |
| Solution 2 | mat3e |
| Solution 3 |
