博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
junit mockito_Mockito存根异常– JUnit,TestNG
阅读量:2533 次
发布时间:2019-05-11

本文共 2305 字,大约阅读时间需要 7 分钟。

junit mockito

Sometimes our methods throw exceptions and we want to mock the object and test the exceptions. We can use Mockito mock objects with when() and thenThrow() to mock this scenario.

有时,我们的方法会抛出异常,我们想模拟对象并测试异常。 我们可以将Mockito模拟对象与when()thenThrow()来模拟这种情况。

Mockito存根异常– JUnit 5 (Mockito Stub Exception – JUnit 5)

Let’s see a simple example where we will mock our object method to throw an exception. Then we will use assertThrows to test the exception and its message.

让我们看一个简单的示例,在该示例中我们将模拟对象方法以引发异常。 然后,我们将使用 assertThrows测试异常及其消息。

package com.journaldev.mockito.examples;import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertThrows;import static org.mockito.Mockito.mock;import static org.mockito.Mockito.when;import java.util.List;import org.junit.jupiter.api.Test;class JUnitMockitoStubExceptions {	@SuppressWarnings("unchecked")	@Test	void test() {		List
list = mock(List.class); when(list.size()).thenThrow(new RuntimeException("size() method not supported")); Exception exception = assertThrows(RuntimeException.class, () -> list.size()); assertEquals("size() method not supported", exception.getMessage()); }}

For simplicity, I am mocking List interface. Similarly, we can mock any other object too and specify its behavior to throw an exception when a specific method is called.

为简单起见,我在模拟List接口。 同样,我们也可以模拟其他任何对象,并指定其行为以在调用特定方法时引发异常。

Mockito存根异常– TestNG (Mockito Stub Exception – TestNG)

If you are using framework, then we can use assertThrows assertion.

如果您使用的是框架,则可以使用assertThrows断言。

@Testvoid test() {	List
list = mock(List.class); when(list.size()).thenThrow(new RuntimeException("size() method not supported")); assertThrows(RuntimeException.class, () -> list.size());}

If we want to test exception message too, then we can use @Test annotation expectedExceptions and expectedExceptionsMessageRegExp attributes.

如果我们要测试异常消息太过,那么我们就可以用@Test注解expectedExceptionsexpectedExceptionsMessageRegExp属性。

@Test(expectedExceptions = RuntimeException.class, expectedExceptionsMessageRegExp = "size method not supported")void test1() {	List
list = mock(List.class); when(list.size()).thenThrow(new RuntimeException("size method not supported")); list.size();}
. 下载完整的项目代码。

翻译自:

junit mockito

转载地址:http://uoqzd.baihongyu.com/

你可能感兴趣的文章
学习操作系统导图
查看>>
在线的JSON formate工具
查看>>
winform非常实用的程序退出方法!!!!!(转自博客园)
查看>>
xml解析
查看>>
centos安装vim
查看>>
linux工作调度(计划任务)
查看>>
hdu--1698 Just a Hook(线段树+区间更新+懒惰标记)
查看>>
Python学习笔记-EXCEL操作
查看>>
二月二——头牙诗词
查看>>
《吴忠与富平》之四:汉三水属国(北地属国、安定属国)
查看>>
丁酉立秋喜逢风雨
查看>>
vim删除#开头的行和正则表达式笔记
查看>>
python3 提成计算
查看>>
VBA赋值给指定单元格
查看>>
抽象类和接口总结回顾
查看>>
【语言处理与Python】5.3使用Python字典映射词及其属性
查看>>
设备信息
查看>>
Android Volley框架的使用(三)
查看>>
[错误总结] 控件frame设置无效
查看>>
Redis Java API
查看>>