SpringBoot 单元测试 详解SpringBoot之添加单元测试

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

SpringBoot 单元测试 详解SpringBoot之添加单元测试

木叶之荣   2021-03-24 我要评论
想了解详解SpringBoot之添加单元测试的相关内容吗,木叶之荣在本文为您仔细讲解SpringBoot 单元测试的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:SpringBoot,单元测试,SpringBoot,添加单元测试,下面大家一起来学习吧。

本文介绍了详解SpringBoot之添加单元测试,分享给大家,希望此文章对各位有所帮助

在SpringBoot里添加单元测试是非常简单的一件事,我们只需要添加SpringBoot单元测试的依赖jar,然后再添加两个注解就可搞定了。

首先我们来添加单元测试所需要的jar

<dependency> 
  <groupId>org.springframework.boot</groupId> 
  <artifactId>spring-boot-starter-test</artifactId> 
</dependency> 

接着我们写了一个单元测试的demo

package com.zkn.learnspringboot.service.test; 
 
import com.zkn.learnspringboot.FirstExample; 
import com.zkn.learnspringboot.service.PersonService; 
import org.junit.Test; 
import org.junit.runner.RunWith; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.boot.test.context.SpringBootTest; 
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 
 
/** 
 * Created by wb-zhangkenan on 2016/11/18. 
 */ 
@RunWith(SpringJUnit4ClassRunner.class) 
@SpringBootTest(classes = FirstExample.class) 
public class TestService extends BaseTestService{ 
  @Autowired 
  private PersonService personService; 
  @Test 
  public void testSys() { 
    System.out.println(personService.getPersonDomain().toString()); 
  } 
 
} 

然后我们run一下,一个单元测试就搞定了。

另外:@RunWith和@SprintBootTest这两个注解上都有@Inherited这个注解,所以我们可以定义一个单元测的父类,然后所有的单元测试类继承这个父类就行了。如下所示:

package com.zkn.learnspringboot.service.test; 
 
import com.zkn.learnspringboot.FirstExample; 
import org.junit.runner.RunWith; 
import org.springframework.boot.test.context.SpringBootTest; 
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 
 
/** 
 * Created by zkn on 2016/11/20. 
 */ 
@RunWith(SpringJUnit4ClassRunner.class) 
@SpringBootTest(classes = FirstExample.class) 
public class BaseTestService { 
 
} 
package com.zkn.learnspringboot.service.test; 
 
import com.zkn.learnspringboot.service.PersonService; 
import org.junit.Test; 
import org.springframework.beans.factory.annotation.Autowired; 
 
/** 
 * Created by wb-zhangkenan on 2016/11/18. 
 */ 
 
public class TestService extends BaseTestService{ 
  @Autowired 
  private PersonService personService; 
  @Test 
  public void testSys() { 
    System.out.println(personService.getPersonDomain().toString()); 
  } 
 
} 

如果你用的SpringBoot是1.4.0之前的话,所用的注解稍有不同。你需要把@SpringBootTest注解换成@SpringApplicationConfiguration和@WebAppConfiguration。

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们