美文网首页
Spring中使用单元测试SpringTest

Spring中使用单元测试SpringTest

作者: 墨色尘埃 | 来源:发表于2020-05-21 16:01 被阅读0次

使用Spring测试套件后,代码是如何变优雅的。

1. 加入依赖包

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

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

<dependency>  
            <groupId>junit</groupId>  
            <artifactId>junit</artifactId>  
            <version>4.9</version>  
            <scope>test</scope>  
        </dependency>   
<dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-test</artifactId>  
            <version> 3.2.4.RELEASE  </version>  
            <scope>provided</scope>  
</dependency> 

2. 创建测试源目录和包

在此,推荐创建一个和src平级的源文件目录,因为src内的类都是为日后产品准备的,而此处的类仅仅用于测试。而包的名称可以和src中的目录同名,这样由于在test源目录中,所以不会有冲突,而且名称又一模一样,更方便检索。这也是Maven的约定。


image.png

有几个注意事项:

① 在测试类中不能一级包名不能以java开头,否则会报错
报错原因
② 测试类的包名要和src中的目录同名,否则Spring boot junit无法注入对象的依赖关系
Spring boot junit无法注入service对象

那么为什么测试类的包名要和src中的目录同名呢?

SpringBoot自动装配原理分析一文中,我们知道最后读取了启动类所在的包名,即src目录名。所以映衬了上面的原因

image.png

3. 创建测试类

1)基类,其实就是用来加载配置文件的

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

2)接着是我们自己的测试类

使用@RunWith@SpringBootTest注解

//@RunWith(Junit.class)
//@RunWith(SpringRunner.class)
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = App.class)
public class StreamTest {

    @Autowired
    OrganizationService service;

    @Test
    public void test4() {
        List<Organization> organizations = service.selectList(new EntityWrapper<>());
        Map<String, List<Organization>> collect = organizations.stream().collect(Collectors.groupingBy(new Function<Organization, String>() {
            @Override
            public String apply(Organization organization) {
                return organization.getpOrgId();
            }
        }));
        System.out.println(collect);
    }

}

Springboot测试类之@RunWith注解

@RunWith就是一个运行器
@RunWith(JUnit4.class)就是指用JUnit4来运行
@RunWith(SpringJUnit4ClassRunner.class),让测试运行于Spring测试环境
@RunWith(Suite.class)的话就是一套测试集合

想要在spring环境下运行,则@RunWith+@SpringBootTest注解一起使用

不想要在spring环境下运行,则使用@RunWith注解

相关文章

网友评论

      本文标题:Spring中使用单元测试SpringTest

      本文链接:https://www.haomeiwen.com/subject/cmozohtx.html