简体   繁体   中英

Running a Spring context test using programatic TestNG

I want to run my integration test programatically using the TestNG API

I figured that this can be done using

TestListenerAdapter tla = new TestListenerAdapter();
org.testng.TestNG testng = new org.testng.TestNG();
testng.setTestClasses(new Class[] { SomeTest.class });
testng.addListener(tla);
testng.run();

Now in the SomeTest class I have some spring resources autowired. I initialized the spring context but it seems that when TestNG runs the class it creates a new instance of the SomeTest.class by itself and not necessarily using Spring and then all the Autowiring that has happened thru the spring container and the @Autowired tag is lost. ( This is what my initial guess is and I may be wrong)

Is there a way that I can run the tests so that TestNG obtains the instance thru the Spring context.

You should take a test dependency on SpringTest and use one of the solutions from their testing documentation .

@ContextConfiguration(locations = { "classpath:spring-test-config.xml" })
public class SomeSpringTest extends AbstractTestNGSpringContextTests {
    @Autowired
    private SomeClass someClass;

    @Test
    public void someTest() {
        ...
    }
}

If you need transactional support you can use AbstractTransactionalTestNGSpringContextTests . Here is a relevant snippet from their documentation about accessing the applicationContext in AbstractTestNGSpringContextTests :

AbstractTestNGSpringContextTests is an abstract base test class that integrates the Spring TestContext Framework with explicit ApplicationContext testing support in a TestNG environment. When you extend AbstractTestNGSpringContextTests, you can access a protected applicationContext instance variable that can be used to perform explicit bean lookups or to test the state of the context as a whole.

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