• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

详解SpringBoot之添加单元测试

springboot 搞代码 4年前 (2022-01-05) 30次浏览 已收录 0个评论

本篇文章主要介绍了详解SpringBoot之添加单元测试,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

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

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

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

  org.springframework.bootspring-boot-starter-test

接着我们写了一个单元测试的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.SpringJU<em style="color:transparent">来源[email protected]搞@^&代*@码网</em>nit4ClassRunner; /** * 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。

以上就是详解SpringBoot之添加单元测试的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:详解SpringBoot之添加单元测试

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址