junit mockito_Mockito存根异常– JUnit,TestNG

本文介绍了如何使用Mockito在JUnit 5和TestNG中模拟对象方法,使其在调用时抛出异常。通过具体的示例展示了如何测试异常及其消息,以确保正确处理错误情况。
摘要由CSDN通过智能技术生成

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 JUnit 5 assertThrows to test the exception and its message.

让我们看一个简单的示例,在该示例中我们将模拟对象方法以引发异常。 然后,我们将使用JUnit 5 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<String> 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 TestNG framework, then we can use assertThrows assertion.

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

@Test
void test() {
	List<String> 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<String> list = mock(List.class);
	when(list.size()).thenThrow(new RuntimeException("size method not supported"));
	list.size();
}
GitHub Repository. GitHub Repository下载完整的项目代码。

翻译自: https://www.journaldev.com/21831/mockito-stub-exception-junit-testng

junit mockito

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值