单元测试是正规项目开发过程中不可缺少的,sonar等工具可以统计项目代码的测试覆盖率。 从测试代码的覆盖率可以从侧面反应整个代码执行中可能出现问题的概率,因此大公司的项目对单体测试覆盖率有明确的要求。
作为当前微服务开发基础的springboot需要对该框架进行单元测试,特别是对控制器接口进行单元测试进行必要的研究。 springboot为单元测试提供了很多辅助注释。 了解这些评论后,可以使用这些特性轻松进行微服务的单元测试。
本文只论述控制器接口方面的单元测试,首先看@WebMvcTest这个评论
@target(elementtype.type ) retention ) retentionpolicy.runtime ) documented @ inherited @ bootstrap with ) webmvctestestestestth autoconfiguration ) enabled=false ) typeexcludefilters ) webmvctypeexclllation ) typexcllaters @ auto configurater uremockmvc @ importautoconfigurationpublic @ interfacewebmvctest {/* } properties inform { @ literal key=value } thatshould bbbby beforethetestruns.* @ returnthepropertiestoadd * @ since2.1.0*/string [ ] properties () default {} );/* * specifiesthecontrollerstotest.thisisanaliasof { @ link # controllers (} which * canbeusedforbrevityifnootheratttributeriaters fordetails.*@see#controllers(* ) () ) ) ) ) ) ) [] value () default {} );/* * specifiesthecontrollerstotest.maybeleftblankifall { @ code @ controller } * beansshouldbeaddedtotheapplicationcontextexter [] controllers () default {} );/* * determinesifdefaultfilteringshouldbeusedwith * { @ linkspringbootapplication @ springbootapplication }.bydefaultonly { (whennoexplicit ) @link#controllers ) (controllers ) are*defined )、{ @ code @ controller advice } and { @ codewebmvcocod include filters (* @ see # excl lled @ returnifdefaultfiltersshouldbeused */booleanusedefaultfilters () default true;/* * asetofincludefilterswhichcanbeusedtoaddotherwisefilteredbeanstothe *应用程序上下文. * @ returnincludefilterstoapplothe asetofexcludefilterswhichcanbeusedtofilterbeansthatwouldotherwisebe * addedtotheapplicationcontext.* @ return exclude/* * auto-configurationexclusionsthatshouldbeappliedforthistest.* @ return auto-configurationexclusionstoapply */@ alias for [] excludeAutoConfiguration () default {} ); } 1,@WebMvcTest注释与@SpringBootTest注释不兼容。 根据上面@WebMvcTest注释的定义,注释@WebMvcTest支持指定控制器的接口测试,从而减少不必要的组件加载时间。 2,@WebMvcTest注释默认扫描@Controller,@ControllerAdvice,@JsonComponent,Converter/GenericConverter,Filter, 有一个名为webmvcconfigurerandhandlermethodargumentresolver的组件,但不会扫描@Component、@Service or @Repository等组件
@MockBean
隐私保护服务;
@Autowired
私有服务器服务器;
@Test
void exampleTest (
远程服务模拟someCall接口调用的返回值
given (this.remoteservice.some call () ).willreturn ) ' mock );
string reverse=reverser.reversesomecall (;
资产that (reverse ).isequalto ) (kcom );
}
3、如果想使用数据库的实际值进行测试,同时测试服务的相关接口流程,也可以使用@ springboottest @ autoconfiguremockmvc注释的合作方式完成。
总结,本文介绍了两种方式:
1、用@WebMvcTest和@mockbean(mockcontroller定义的服务接口)进行评论
2、通过@SpringBootTest和@AutoConfigureMockMvc评论实现