Unit testing with TestNG 6 using Spring's application context
TestNG tests are run outside Spring; Spring is not initialized before the tests are run. To be able to use the beans defined in the configuration files and dependency injection, some bootstrapping code needs to be added to the test class.
How to do it…
Follow these steps to test a method using the Spring application context with TestNG 6:
Add the
spring-test
Maven dependency inpom.xml
:<dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.1.1.RELEASE</version> <scope>test</scope> </dependency>
Make the test class extend
AbstractTestNGSpringContextTests
and add these annotations to it:@ContextConfiguration(classes = {AppConfig.class}) @WebAppConfiguration public class TestControllerTest extends AbstractTestNGSpringContextTests { …
Use Spring beans as usual, for example, as
@Autowired
fields:@Autowired private UserDAO userDAO...