Java Mockito 如何模拟和断言抛出的异常?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16243580/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mockito How to mock and assert a thrown exception?
提问by stackoverflow
I'm using mockito in a junit test. How do you make an exception happen and then assert that it has (generic pseudo-code)
我在junit测试中使用mockito。你如何使异常发生然后断言它有(通用伪代码)
采纳答案by MariuszS
BDDStyle Solution (Updated to Java 8)
BDD风格解决方案(更新到 Java 8)
Mockitoalone is not the best solution for handling exceptions, use Mockitowith Catch-Exception
的Mockito本身并不是处理异常的最佳解决方案,使用的Mockito与捕捉的异常
Mockito + Catch-Exception+ AssertJ
Mockito + Catch-Exception+ AssertJ
given(otherServiceMock.bar()).willThrow(new MyException());
when(() -> myService.foo());
then(caughtException()).isInstanceOf(MyException.class);
Sample code
示例代码
Dependencies
依赖关系
回答by NilsH
To answer your second question first. If you're using JUnit 4, you can annotate your test with
先回答你的第二个问题。如果您使用的是 JUnit 4,则可以使用
@Test(expected=MyException.class)
to assert that an exception has occured. And to "mock" an exception with mockito, use
断言发生了异常。并用mockito“模拟”异常,使用
when(myMock.doSomething()).thenThrow(new MyException());
回答by Duncan Jones
Make the exception happen like this:
使异常像这样发生:
when(obj.someMethod()).thenThrow(new AnException());
Verify it has happened either by asserting that your test will throw such an exception:
通过断言您的测试将抛出这样的异常来验证它是否发生了:
@Test(expected = AnException.class)
Or by normal mock verification:
或者通过正常的模拟验证:
verify(obj).someMethod();
The latter option is required if your test is designed to prove intermediate code handles the exception (i.e. the exception won't be thrown from your test method).
如果您的测试旨在证明中间代码处理异常(即不会从您的测试方法抛出异常),则需要后一个选项。
回答by Selwyn
Updated answer for 06/19/2015 (if you're using java 8)
2015 年 6 月 19 日更新的答案(如果您使用的是 java 8)
Just use assertj
只需使用 assertj
Using assertj-core-3.0.0 + Java 8 Lambdas
使用 assertj-core-3.0.0 + Java 8 Lambdas
@Test
public void shouldThrowIllegalArgumentExceptionWhenPassingBadArg() {
assertThatThrownBy(() -> myService.sumTingWong("badArg"))
.isInstanceOf(IllegalArgumentException.class);
}
Reference: http://blog.codeleak.pl/2015/04/junit-testing-exceptions-with-java-8.html
参考:http: //blog.codeleak.pl/2015/04/junit-testing-exceptions-with-java-8.html
回答by Prashant Kumar
If you're using JUnit 4, and Mockito 1.10.x Annotate your test method with:
如果您使用的是 JUnit 4 和 Mockito 1.10.x,请使用以下内容注释您的测试方法:
@Test(expected = AnyException.class)
and to throw your desired exception use:
并抛出您想要的异常使用:
Mockito.doThrow(new AnyException()).when(obj).callAnyMethod();
回答by Daniel Treiber
If you want to test the exception message as well you can use JUnit's ExpectedException with Mockito:
如果您还想测试异常消息,您可以将 JUnit 的 ExpectedException 与 Mockito 一起使用:
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Test
public void testExceptionMessage() throws Exception {
expectedException.expect(AnyException.class);
expectedException.expectMessage("The expected message");
given(foo.bar()).willThrow(new AnyException("The expected message"));
}
回答by Anupama Boorlagadda
Using mockito, you can make the exception happen.
使用 mockito,您可以使异常发生。
when(testingClassObj.testSomeMethod).thenThrow(new CustomException());
when(testingClassObj.testSomeMethod).thenThrow(new CustomException());
Using Junit5, you can assert exception, asserts whether thatexception is thrown when testing methodis invoked.
使用 Junit5,您可以断言异常,断言在调用测试方法时是否抛出该异常。
@Test
@DisplayName("Test assert exception")
void testCustomException(TestInfo testInfo) {
final ExpectCustomException expectEx = new ExpectCustomException();
InvalidParameterCountException exception = assertThrows(InvalidParameterCountException.class, () -> {
expectEx.constructErrorMessage("sample ","error");
});
assertEquals("Invalid parametercount: expected=3, passed=2", exception.getMessage());
}
Find a sample here: assert exception junit
在此处查找示例:断言异常 junit
回答by eel ghEEz
Unrelated to mockito, one can catch the exception and assert its properties. To verify that the exception did happen, assert a false condition within the try block after the statement that throws the exception.
与 mockito 无关,可以捕获异常并断言其属性。要验证异常确实发生了,请在抛出异常的语句之后的 try 块中断言假条件。
回答by Sam
Assert by exception message:
通过异常消息断言:
try {
MyAgent.getNameByNode("d");
} catch (Exception e) {
Assert.assertEquals("Failed to fetch data.", e.getMessage());
}
回答by JediCate
Or if your exception is thrown from the constructor of a class:
或者,如果您的异常是从类的构造函数中抛出的:
@Rule
public ExpectedException exception = ExpectedException.none();
@Test
public void myTest() {
exception.expect(MyException.class);
CustomClass myClass= mock(CustomClass.class);
doThrow(new MyException("constructor failed")).when(myClass);
}