1、Spring的org.springframework.test.context.testng包为基于TestNG的测试用例提供了支持类:AbstractTestNGSpringContextTests对集成了Spring TestContext Framework
与TestNG环境中的ApplicationContext测试支持的基础测试类进行了抽象。当你继承AbstractTestNGSpringContextTests时,就可以访问到下列protected的成员变量:
applicationContext:使用它进行显式的bean查找或者测试整个上下文的状态。在测试类上使用 @TestExecutionListeners 注释标签,可以引入的监听器包括
DependencyInjectionTestExecutionListener:使得测试类拥有依赖注入特性
DirtiesContextTestExecutionListener:使得测试类拥有更新 applicationContext 能力
2、项目依赖
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>${testng.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
3、实例参考如下
如果不指定@WebAppConfiguration(用于声明一个ApplicationContext集成测试加载WebApplicationContext。作用是模拟ServletContext)则会出现下面的错误:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javax.servlet.ServletContext' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
上面的配置需要同时读取注解配置和xml配置,这里的@ContextConfiguration只解析了部分,如果项目中还存在其他模块的applicationContext,也需要把他们引进来,@WebAppConfiguration(value = "src/main/webapp") //默认是src/main/webapp
如果我不指定@WebAppConfiguration还会出现这种问题:propertyFileConfigurer.xml有个这样的配置,如果没有指定@WebAppConfiguration,则只能用注释掉的value去读取cas.properties文件,但是指定了之后,两种方式都可以。
===========================================================================================
如果我们不需要spring相关的任何xml配置,只用Java注解来配置,就可以使用AnnotationConfigContextLoader ,去读取配置,不指定的话也会报错,因为它默认加载ApplicationContext 是用的GenericXmlContextLoader 。具体官方文档可以看这里:Spring 3.1 M2: Testing with @Configuration Classes and Profiles