本文共 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()
来模拟这种情况。
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() { Listlist = 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接口。 同样,我们也可以模拟其他任何对象,并指定其行为以在调用特定方法时引发异常。
If you are using framework, then we can use assertThrows
assertion.
如果您使用的是框架,则可以使用assertThrows
断言。
@Testvoid test() { Listlist = 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注解expectedExceptions
和expectedExceptionsMessageRegExp
属性。
@Test(expectedExceptions = RuntimeException.class, expectedExceptionsMessageRegExp = "size method not supported")void test1() { Listlist = mock(List.class); when(list.size()).thenThrow(new RuntimeException("size method not supported")); list.size();}
翻译自:
junit mockito
转载地址:http://uoqzd.baihongyu.com/