这篇文章将为大家详细讲解有关如何中SpringBoot中添加一个单元测试,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。
首先我们来添加单元测试所需要的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。
关于如何中SpringBoot中添加一个单元测试就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。