作为程序员为了提前发现代码bug,优化代码; 通常我们写完某个功能模块代码后都需要写单元测试对代码块进行测试(特别是敏捷开发中);Java项目最常用的单元测试框架即为Junit(目前最新版本为Junit5),SpringBoot本身也整合了该框架。在写单元测试时代码块中的调到第三方接口方法或涉及数据库操作的接口方法一般都需要mock掉(测试中叫打测试桩)。目前在 Java 中主流的 Mock 测试框架有 Mockito、JMock、EasyMock,Mockito 框架是SpringBoot 目前内建的 框架。本文主要介绍Junit5+Mockito在SpringBoot项目写单元测试的使用。
Mockito,Junit在SpringBoot 内部已依赖只需引入spring-boot-starter-test即可。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
@TestInstance(Lifecycle.PER_CLASS)注解
如果您希望JUnit Jupiter在同一个测试实例上执行所有测试方法,只需使用@TestInstance(Lifecycle.PER_CLASS)注释您的测试类。使用此模式时,每个测试类将创建一个新的测试实例。如果没使用@TestInstance(Lifecycle.PER_CLASS)注解,使用@BeforeAll和@AfterAll注解必须在static静态方法上使用。
- TestInstance.Lifecycle.PER_CLASS:每个测试类将创建一个新的测试实例。
- TestInstance.Lifecycle.PER_METHOD:将为每种测试方法,测试工厂方法或测试模板方法创建一个新的测试实例。此模式类似于JUnit版本1至4中的行为。
@ExtendWith(MockitoExtension.class)注解
用在springboot项目中,涉及spring的单元测试需要使用@ExtendWith(SpringExtension.class)注解,可以mock spring bean。不涉及spring时使用@ExtendWith(MockitoExtension.class)。
@ExtendWith(SpringExtension.class)注解在Spring boot 2.1.x需要配合@SpringBootTest 使用,Spring boot 2.1.x之后可以不使用@ExtendWith(SpringExtension.class)注解
参考文档:Java – 理解 @ExtendWith(SpringExtension.class) 和 @ExtendWith(MockitoExtension.class)之间的差别
@SpringBootTest(classes = Application.class)注解
classes = ApplicationStarter.class指向SpringBoot启动类,启动spring容器。
在不同的Spring Boot版本中@ExtendWith的使用:
其中在Spring boot 2.1.x之前:
@SpringBootTest 需要配合@ExtendWith(SpringExtension.class)才能正常工作的。
而在Spring boot 2.1.x之后:
@SpringBootTest 已经组合了@ExtendWith(SpringExtension.class),因此,无需在进行该注解的使用了,进一步简化。如下图@SpringBootTest注解中已包含@ExtendWith(SpringExtension.class):
基本的注解都是方法上的注解,意思就是只在测试方法上进行添加,对应注解有以下几种:
| 注解 | 说明 |
| @Test | 测试方法的入口;可单独运行 |
| @BeforeEach | 每个测试方法前运行;不可以单独运行该方法 |
| @AfterEach | 每个测试方法后运行;不可以单独运行该方法 |
| @BeforeAll | 在类中所有方法前运行;static修饰;不可单独运行该方法 |
| @AfterAll | 在类中所有方法后运行;static修饰;不可单独运行该方法 |
代码示例:
import org.mockito.InjectMocks;
@TestInstance(Lifecycle.PER_CLASS)
@SpringBootTest(classes = ApplicationStarter.class)
public class DemoServiceImplTest {
@InjectMocks
private DemoService demoService =new DemoServiceImpl();
@BeforeAll
void beforeAllInit() {
System.out.println("running before all");
}
@AfterAll
void afterAllCleanUp() {
System.out.println("running after all");
}
@BeforeEach
void init() {
System.out.println("running before each...");
}
@AfterEach
void cleanUp() {
System.out.println("running after each...");
}
@Test
void testSum() {
assertEquals(2, demoService.addtwoNumbers(1, 1));
}
}
Assertions.assertEquals()值比较校验:
assertEquals(expected, actual,message)里面最少是2个参数,一个自己的期望值「expected」,一个程序的实际值「actual」。如果想要断言失败的情况下显示自定义的说明,则加上第3个参数,即断言失败说明「message」。
Assertions.assertThrows()异常捕获校验:
assertThrows(Class<T> expectedType, Executable executable, String message)去判断代码抛出的异常是业务代码自定义的异常不,对应的期望值变成了异常类型「
Class<T>」的期望值,实际的值也是抛出异常的实际值「Executable」,同样如果想要断言失败的情况下显示自定义的说明,则加上第3个参数,即断言失败说明「message」。
代码示例:
import org.mockito.InjectMocks;
@TestInstance(Lifecycle.PER_CLASS)
@SpringBootTest(classes = ApplicationStarter.class)
public class DemoServiceImplTest {
@InjectMocks
private DemoService demoService =new DemoServiceImpl();
@Test
public void testSum() {
//Assertions.assertThrows()
Exception ex = Assertions.assertThrows(Exception.class, () ->demoService.addtwoNumbers(1, 1))
//Assertions.assertEquals()
Assertions.assertEquals(ex.getMessage(),"test");
}
}
更多详细信息参考文档:test-instance-lifecycle
在测试代码块中经常会调到第三方接口方法(比如第三方SDK接口方法或远程RPC接口),涉及数据库操作的接口方法(数据库增删改查接口)。这些方法需要其他环境服务支持,链接远程数据库,我们只需测试自己编写的单元代码块是否有问题,不想真实调用这些方法。要解决这个问题,可以把这些方法都mock(模拟)掉。Mockito框架提供很好的支持。
@Autowird 等方式完成自动注入。在单元测试中,没有启动 spring 框架,此时就需要通过 @ InjectMocks完成依赖注入。@InjectMocks会将带有@Spy 和@Mock 注解的对象尝试注入到被 测试的目标类中。如下代码示例:
代码示例:
@Component("mock")
public class MockRepository {
public MockData mock(String userName) {
return new MockData(userName);
}
}
import org.mockito.InjectMocks;
@Service
public class DemoServiceImpl {
@Autowired
private UserRepository userRepository;
@Autowired
private ApplicationContext applicationContext;
@Override
public Result getUserInfo(String id) {
User user=userRepository.findUserById(id);
MockRepository mockRepository=applicationContext.getBean("mock");
MockData data=mockRepository.mock(user.getUserName());
return new Result("1000","success",data);
}
}
import org.mockito.InjectMocks;
@TestInstance(Lifecycle.PER_CLASS)
@SpringBootTest(classes = ApplicationStarter.class)
public class DemoServiceImplTest {
@InjectMocks
private DemoService demoService =new DemoServiceImpl();
@Mock
private UserRepository userRepository;
@MockBean
private MockRepository mockRepository;
@Autowired
private ApplicationContext applicationContext;
@Test
public void testSum() {
//Assertions.assertThrows()
Result res =demoService.getUserInfo("test");
//Assertions.assertEquals()
Assertions.assertEquals(res.getCode(),"1000");
}
}
1.when(...) thenReturn(...)会调用真实的方法,如果你不想调用真实的方法而是想要mock的话,就不要使用这个方法。
import org.mockito.InjectMocks;
@TestInstance(Lifecycle.PER_CLASS)
@SpringBootTest(classes = ApplicationStarter.class)
public class DemoServiceImplTest {
@InjectMocks
private DemoService demoService =new DemoServiceImpl();
@Mock
private UserRepository userRepository;
@MockBean
private MockRepository mockRepository;
@Autowired
private ApplicationContext applicationContext;
@Test
public void testSum() {
// when(..).thenReturn(..)
Mockito.when(userRepository.findUserById(Mockito.anyString())).thenReturn(new User());
Result res =demoService.getUserInfo("test");
//Assertions.assertEquals()
Assertions.assertEquals(res.getCode(),"1000");
}
}
2.doReturn(...) when(...) 跟when(...) thenReturn(...)一样都是mock方法,但不会调用真实方法。
import org.mockito.InjectMocks;
@TestInstance(Lifecycle.PER_CLASS)
@SpringBootTest(classes = ApplicationStarter.class)
public class DemoServiceImplTest {
@InjectMocks
private DemoService demoService =new DemoServiceImpl();
@Mock
private UserRepository userRepository;
@MockBean
private MockRepository mockRepository;
@Autowired
private ApplicationContext applicationContext;
@Test
public void testSum() {
// doReturn(new User()).when(userRepository)
Mockito.doReturn(new User()).when(userRepository).findUserById(Mockito.anyString()))
Result res =demoService.getUserInfo("test");
//Assertions.assertEquals()
Assertions.assertEquals(res.getCode(),"1000");
}
}
3.doAnswer…when 当模拟对象调用它的方法,需要执行一些操作(其实就是需要执行一个代码块)才能得到返回值时,则需要使用doAnswer来构造产生这个模拟的返回值。例如:当模拟对象调用某个方法的返回值是个复合值(bean)时,就需要用doAnswer来构造该返回值。
@InjectMocks
private DemoService demoService =new DemoServiceImpl();
@Mock
private StockDao stockDao;
...
@Test
public void stockTest() {
doAnswer(new Answer<StockModel>) {
@Override
public StockModel answer(InvocationOnMock invocation) throws Throwable {
StockModel stock = new StockModel ();
stock.setFundFamilyName("fundFamily01");
return stock;
}
}).when(stockDao).lookup("testStock");
Result res=demoService.stock("testStock");
Assertions.assertEquals(res.getStock(),"test");
}
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看rubyzip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
很好奇,就使用rubyonrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提
假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于
我正在尝试使用ruby和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t
我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h
我想为Heroku构建一个Rails3应用程序。他们使用Postgres作为他们的数据库,所以我通过MacPorts安装了postgres9.0。现在我需要一个postgresgem并且共识是出于性能原因你想要pggem。但是我对我得到的错误感到非常困惑当我尝试在rvm下通过geminstall安装pg时。我已经非常明确地指定了所有postgres目录的位置可以找到但仍然无法完成安装:$envARCHFLAGS='-archx86_64'geminstallpg--\--with-pg-config=/opt/local/var/db/postgresql90/defaultdb/po