七、Spring整合junit

(一)添加依赖

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <!--没有这个依赖,就没有SpringJUnit4ClassRunner.class-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
        </dependency>

(二)测试样例

//启动时创建Spring容器
@RunWith(SpringJUnit4ClassRunner.class)
//指定Spring容器创建时使用哪个配置文件
@ContextConfiguration("classpath:spring/applicationContext.xml")
public class TestJunit {
    /**
     * 不用启动tomcat容器,也可以实现属性注入
     */
    @Resource(name = "user")
    private User user;
}

(三)总结
  以前测试Spring项目中的方法,都是启动tomcat容器,让整个web项目启动,从而启动Spring容器,达到测试依赖注入的目的。这样做,步骤繁琐,而整合了Junit之后,就避免了启动tomcat,从而实现Spring容器启动,测试方法!好!

猜你喜欢

转载自blog.csdn.net/panchang199266/article/details/81914794