简体   繁体   中英

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

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.

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 dataProvider s 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){
            //...
        }

尝试将loader=AnnotationConfigContextLoader.class添加到 ContextConfiguration。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM