详解SpringBoot之添加单元测试
本文介绍了详解SpringBoot之添加单元测试,分享给大家,希望此文章对各位有所帮助
在SpringBoot里添加单元测试是非常简单的一件事,我们只需要添加SpringBoot单元测试的依赖jar,然后再添加两个注解就可搞定了。
首先我们来添加单元测试所需要的jar
org.springframework.boot spring-boot-starter-test
接着我们写了一个单元测试的demo
packagecom.zkn.learnspringboot.service.test;
importcom.zkn.learnspringboot.FirstExample;
importcom.zkn.learnspringboot.service.PersonService;
importorg.junit.Test;
importorg.junit.runner.RunWith;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.boot.test.context.SpringBootTest;
importorg.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
*Createdbywb-zhangkenanon2016/11/18.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes=FirstExample.class)
publicclassTestServiceextendsBaseTestService{
@Autowired
privatePersonServicepersonService;
@Test
publicvoidtestSys(){
System.out.println(personService.getPersonDomain().toString());
}
}
然后我们run一下,一个单元测试就搞定了。
另外:@RunWith和@SprintBootTest这两个注解上都有@Inherited这个注解,所以我们可以定义一个单元测的父类,然后所有的单元测试类继承这个父类就行了。如下所示:
packagecom.zkn.learnspringboot.service.test;
importcom.zkn.learnspringboot.FirstExample;
importorg.junit.runner.RunWith;
importorg.springframework.boot.test.context.SpringBootTest;
importorg.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
*Createdbyzknon2016/11/20.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes=FirstExample.class)
publicclassBaseTestService{
}
packagecom.zkn.learnspringboot.service.test;
importcom.zkn.learnspringboot.service.PersonService;
importorg.junit.Test;
importorg.springframework.beans.factory.annotation.Autowired;
/**
*Createdbywb-zhangkenanon2016/11/18.
*/
publicclassTestServiceextendsBaseTestService{
@Autowired
privatePersonServicepersonService;
@Test
publicvoidtestSys(){
System.out.println(personService.getPersonDomain().toString());
}
}
如果你用的SpringBoot是1.4.0之前的话,所用的注解稍有不同。你需要把@SpringBootTest注解换成@SpringApplicationConfiguration和@WebAppConfiguration。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。