如何junit和spring注解进行整合做单元测试
1、首先添加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>

2、junit的test类上添加@RunWith(SpringJUnit4ClassRunner.class@ContextConfiguration(locations = "classpath:applicationContext.xml")两个注解,@RunWith指定SpringJUnit4ClassRunner类为junit测试运行器,@ContextConfiguration指定spring的配置文件路径

3、通过以上配置之后,则可以直接在类成员属性上添加@Autowired注解进行注入@AutowiredRedisTemplate redisTemplate;

4、添加testCase方法,@Testpublic void testPutOne() throws InterruptedException { redisTemplate.opsForValue().set("testKey", "testValue"); String testValue = (String)redisTemplate.opsForValue().get("testKey"); Assert.assertEquals(testValue, "testValue");}

5、Assert类是junit类库,有很多断言的方法,可以用来判断测试结果是否是预期的结果

6、运行testPutOne测试方法,结果显示 1 test passed

7、通过上面例子可以看出,使用spring-test的注解结合junit进行测试,可以更加简介方便的测试基于spring开发的项目代码