在基于spring框架做项目开发时,写junit单元测试需要在spring的环境下运行测试用例,需要加载spring的配置环境信息,之前我们可以使用编码的方式来实现spring的环境启动,现在介绍下如何使用注解的方式,简单方便的使junit和spring进行整合测试
工具/原料
-
spring
-
junit
方法/步骤
-
首先添加maven依赖的jar文件,spring的依赖在此不列举了,在做junit和spring的整合单元测试,需要依赖spring-test和junit
<junit.version>4.11</junit.version>
<spring.version>4.0.6.RELEASE</spring.version>
<!-- 测试相关jar包 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
-
junit的test类上添加
@RunWith(SpringJUnit4ClassRunner.class
@ContextConfiguration(locations = "classpath:applicationContext.xml")
两个注解,@RunWith指定SpringJUnit4ClassRunner类为junit测试运行器,@ContextConfiguration指定spring的配置文件路径
-
通过以上配置之后,则可以直接在类成员属性上添加@Autowired注解进行注入
@AutowiredRedisTemplate redisTemplate;
-
添加testCase方法,
@Test
public void testPutOne() throws InterruptedException {
redisTemplate.opsForValue().set("testKey", "testValue");
String testValue = (String)redisTemplate.opsForValue().get("testKey");
Assert.assertEquals(testValue, "testValue");
}
-
Assert类是junit类库,有很多断言的方法,可以用来判断测试结果是否是预期的结果
-
运行testPutOne测试方法,结果显示 1 test passed
-
7
通过上面例子可以看出,使用spring-test的注解结合junit进行测试,可以更加简介方便的测试基于spring开发的项目代码