如何Junit和spring注解进行整合做单元测试

在基于spring框架做项目开发时,写junit单元测试需要在spring的环境下运行测试用例,需要加载spring的配置环境信息,之前我们可以使用编码的方式来实现spring的环境启动,现在介绍下如何使用注解的方式,简单方便的使junit和spring进行整合测试

工具/原料

  • spring

  • junit

方法/步骤

  1. 首先添加maven依赖的jar文件,spring的依赖在此不列举了,在做junit和spring的整合单元测试,需要依赖spring-test和junit

    4.11

    4.0.6.RELEASE

     

        junit

        junit

        ${junit.version}

        test

        org.springframework

        spring-test

        ${spring.version}

        test

    如何Junit和spring注解进行整合做单元测试_第1张图片

  2. junit的test类上添加

    @RunWith(SpringJUnit4ClassRunner.class

    @ContextConfiguration(locations = "classpath:applicationContext.xml")

    两个注解,@RunWith指定SpringJUnit4ClassRunner类为junit测试运行器,@ContextConfiguration指定spring的配置文件路径

    如何junit和spring注解进行整合做单元测试

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

    @AutowiredRedisTemplate redisTemplate;

    如何junit和spring注解进行整合做单元测试

  4. 添加testCase方法,

    @Test

    public void testPutOne() throws InterruptedException {

        redisTemplate.opsForValue().set("testKey", "testValue");

        String testValue = (String)redisTemplate.opsForValue().get("testKey");

        Assert.assertEquals(testValue, "testValue");

    }

    如何Junit和spring注解进行整合做单元测试_第2张图片

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

    如何Junit和spring注解进行整合做单元测试_第3张图片

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

    如何Junit和spring注解进行整合做单元测试_第4张图片

  7. 7

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

你可能感兴趣的:(Junit)