[英]Mockito How to mock and assert a thrown exception?
I'm using mockito in a junit test.我在junit测试中使用mockito。 How do you make an exception happen and then assert that it has (generic pseudo-code)
你如何使异常发生然后断言它有(通用伪代码)
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());
Mockito alone is not the best solution for handling exceptions, use Mockito with Catch-Exception单独的Mockito不处理异常的最佳解决方案,使用具有的Mockito捕捉的异常
given(otherServiceMock.bar()).willThrow(new MyException());
when(() -> myService.foo());
then(caughtException()).isInstanceOf(MyException.class);
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"));
}
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
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();
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 (ie the exception won't be thrown from your test method).如果您的测试旨在证明中间代码处理异常(即不会从您的测试方法中抛出异常),则需要后一个选项。
Use Mockito's doThrow and then catch the desired exception to assert it was thrown later.使用Mockito 的 doThrow然后捕获所需的异常以断言它是稍后抛出的。
@Test
public void fooShouldThrowMyException() {
// given
val myClass = new MyClass();
val arg = mock(MyArgument.class);
doThrow(MyException.class).when(arg).argMethod(any());
Exception exception = null;
// when
try {
myClass.foo(arg);
} catch (MyException t) {
exception = t;
}
// then
assertNotNull(exception);
}
Using mockito, you can make the exception happen.使用 mockito,您可以使异常发生。
when(testingClassObj.testSomeMethod).thenThrow(new CustomException());
Using Junit5, you can assert exception, asserts whether that exception is thrown when testing method is 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
I think this should do it for you.我认为这应该为你做。
assertThrows(someException.class, ()-> mockedServiceReference.someMethod(param1,parme2,..)); assertThrows(someException.class, ()-> mockedServiceReference.someMethod(param1,parme2,..));
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);
}
Unrelated to mockito, one can catch the exception and assert its properties.与 mockito 无关,可以捕获异常并断言其属性。 To verify that the exception did happen, assert a false condition within the try block after the statement that throws the exception.
要验证异常确实发生了,请在抛出异常的语句之后的 try 块中断言假条件。
Assert by exception message:通过异常消息断言:
try {
MyAgent.getNameByNode("d");
} catch (Exception e) {
Assert.assertEquals("Failed to fetch data.", e.getMessage());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.