spring如何整合Junit

可在测试类内中使用@Autowired进行自动注入

添加依赖

使用spring的测试框架需要加入以下依赖包:
JUnit 4 (官方下载:http://www.junit.org/)
Spring Test (Spring框架中的test包)
Spring 相关其他依赖包(不再赘述了,就是context等包)

如果使用maven,在基于spring的项目中添加如下依赖:

<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.12</version>
  <scope>test</scope>
</dependency>
<!--spring-test的版本号需要与spring-mvc的版本号一致-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>4.3.19.RELEASE</version>
    <scope>test</scope>
</dependency>

创建测试类

创建测试包

在项目src目录下新建文件夹

image-20220509125432402

image-20220509125548875

创建与main同级别的test包

image-20220509125346729

创建测试类

import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 
@RunWith(SpringJUnit4ClassRunner.class) //使用junit4进行测试
@ContextConfiguration(locations={"classpath:applicationContext.xml"}) //加载配置文件 
//------------如果加入以下代码,所有继承该类的测试类都会遵循该配置,也可以不加,在测试类的方法上///控制事务,参见下一个实例  
//这个非常关键,如果不加入这个注解配置,事务控制就会完全失效!  
//@Transactional  
//这里的事务关联到配置文件中的事务控制器(transactionManager = "transactionManager"),同时//指定自动回滚(defaultRollback = true)。这样做操作的数据才不会污染数据库!  
//@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)  
//------------  
public class ServiceTest{
    
}

注解解释:

  • @RunWith:用于指定junit运行环境,是junit提供给其他框架测试环境接口扩展,为了便于使用spring的依赖注入,spring提供了org.springframework.test.context.junit4.SpringJUnit4ClassRunner作为Junit测试环境
  • @ContextConfiguration({“classpath:applicationContext.xml”,“classpath:spring/buyer/applicationContext-service.xml”})
    导入配置文件,这里我的applicationContext配置文件是根据模块来分类的。如果有多个模块就引入多个“applicationContext-service.xml”文件。如果所有的都是写在“applicationContext.xml”中则这样导入:
  • @ContextConfiguration(locations = “classpath:applicationContext.xml”)
  • @TransactionConfiguration(transactionManager = “transactionManager”, defaultRollback = true)这里的事务关联到配置文件中的事务控制器(transactionManager = “transactionManager”),同时指定自动回滚(defaultRollback = true)。这样做操作的数据才不会污染数据库!
  • @Transactional:这个非常关键,如果不加入这个注解配置,事务控制就会完全失效!
  • AbstractTransactionalDataSourceSpringContextTests要想构建这一系列的无污染纯绿色事务测试框架就必须找到这个基类!(即所有事务均不生效)

测试是否成功

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:dubbo-zk-provider.xml")
public class ServiceTest {
    @Autowired
    private SomeService someService;
    @Test
    public void test1(){
        String lzj = someService.hello("lzj");
        System.out.println(lzj);
    }
}

image-20220509130035832

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐