当前位置: 代码网 > it编程>编程语言>Java > Maven项目中Junit对Spring进行单元测试方式

Maven项目中Junit对Spring进行单元测试方式

2026年05月10日 Java 我要评论
主要步骤:1.在工程的pom文件中增加spring-test的依赖<dependency> <groupid>org.springframework</groupi

主要步骤:

1.在工程的pom文件中增加spring-test的依赖

<dependency>
    <groupid>org.springframework</groupid>
    <artifactid>spring-test</artifactid>
<version>${spring.version}</version>
</dependency>

2.使用springframework提供的单元测试

新建测试类,并在该类上加上两个注解:

  • @runwith(springjunit4classrunner.class)
  • @contextconfiguration(locations={“classpath*:applicationcontext.xml”})
  • @runwith 大家并不陌生,junit4里用它来做junit加载器
  • @contextconfiguration 主要用来加载spring的配置文件路径:是一个字符串数组,可以加载多个spring配置文件

测试代码如下:

import static org.junit.assert.assertequals;
import org.junit.test;
import org.junit.runner.runwith;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.context.applicationcontext;
import org.springframework.test.context.contextconfiguration;
import org.springframework.test.context.junit4.springjunit4classrunner;
@runwith(springjunit4classrunner.class)
@contextconfiguration(locations = {"classpath:applicationcontext.xml"})
public class empolyeetest {
    @autowired
    applicationcontext ctx; 
    @test
    public void testemployee(){
        employee employee =(employee) ctx.getbean("employee");
        assertequals("zhangsan",employee.getname());
    }
}

3.封装基于abstractjunit4springcontexttests的测试基类

import org.junit.test;
import org.junit.runner.runwith;
import org.springframework.context.applicationcontext;
import org.springframework.test.context.contextconfiguration;
import org.springframework.test.context.junit4.abstractjunit4springcontexttests;
import org.springframework.test.context.junit4.springjunit4classrunner;
@runwith(springjunit4classrunner.class)
@contextconfiguration(locations={"classpath*:applicationcontext.xml"})
public class springtest extends abstractjunit4springcontexttests { 
   public <t> t getbean(class<t> type){
       return applicationcontext.getbean(type);
   }
   public object getbean(string beanname){
       return applicationcontext.getbean(beanname);
   }
   protected applicationcontext getcontext(){
       return applicationcontext;
   }

然后其他测试类只需要继承该类即可,可以省去每次都要绑定application对象。

4.当项目变得复杂

其中的spring配置文件被拆分成了多个,这样该如何引入多个配置文件呢?如下:

@runwith(springjunit4classrunner.class)  
@contextconfiguration(locations = { "classpath*:spring-ctx-service.xml", "classpath*:spring-ctx-dao.xml" })

这样就可以轻松的引入多个spring的配置文件了。

或者配置符合某一个正则表达式的一类文件,如:

 @runwith(springjunit4classrunner.class) 
 @contextconfiguration(locations = "classpath*:spring-ctx-*.xml") 

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com