如何模拟和断言抛出的异常?

时间:2021-08-06 20:30:12

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。如何使异常发生,然后断言它有(通用伪代码)

9 个解决方案

#1


57  

BDD Style Solution

Mockito alone is not the best solution for handling exceptions, use Mockito with Catch-Exception

单独使用Mockito并不是处理异常的最佳解决方案,使用Mockito和Catch-Exception

Mockito + Catch-Exception + AssertJ

given(otherServiceMock.bar()).willThrow(new MyException());

when(myService).foo();

then(caughtException()).isInstanceOf(MyException.class);

Sample code

Dependencies

  • eu.codearte.catch-exception:catch-exception:1.3.3
  • eu.codearte.catch-exception:catch-exception:1.3.3
  • org.assertj:assertj-core:1.7.0
  • org.assertj:assertj-core:1.7.0

Disadvantage

  • Only Mockito up to 1.10.8 is supported
  • 只有Mockito可以达到1.10.8

#2


136  

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());

#3


12  

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).

如果您的测试被设计成证明中间代码处理异常(例如,异常不会从您的测试方法中抛出),则需要后面的选项。

#4


11  

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"));
}

#5


8  

Updated answer for 06/19/2015 (if you're using java 8)

06/19/2015更新答案(如果您使用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 -测试-例外- - java - 8. - html

#6


6  

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();

#7


1  

Using mockito, you can make the exception happen.

使用mockito,您可以使异常发生。

when(testingClassObj.testSomeMethod).thenThrow(new CustomException());

当(testingClassObj.testSomeMethod)。thenThrow(新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

在这里找到一个示例:assert exception junit

#8


-1  

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块中断言一个false条件。

#9


-1  

Assert by exception message:

维护异常消息:

    try {
        MyAgent.getNameByNode("d");
    } catch (Exception e) {
        Assert.assertEquals("Failed to fetch data.", e.getMessage());
    }

#1


57  

BDD Style Solution

Mockito alone is not the best solution for handling exceptions, use Mockito with Catch-Exception

单独使用Mockito并不是处理异常的最佳解决方案,使用Mockito和Catch-Exception

Mockito + Catch-Exception + AssertJ

given(otherServiceMock.bar()).willThrow(new MyException());

when(myService).foo();

then(caughtException()).isInstanceOf(MyException.class);

Sample code

Dependencies

  • eu.codearte.catch-exception:catch-exception:1.3.3
  • eu.codearte.catch-exception:catch-exception:1.3.3
  • org.assertj:assertj-core:1.7.0
  • org.assertj:assertj-core:1.7.0

Disadvantage

  • Only Mockito up to 1.10.8 is supported
  • 只有Mockito可以达到1.10.8

#2


136  

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());

#3


12  

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).

如果您的测试被设计成证明中间代码处理异常(例如,异常不会从您的测试方法中抛出),则需要后面的选项。

#4


11  

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"));
}

#5


8  

Updated answer for 06/19/2015 (if you're using java 8)

06/19/2015更新答案(如果您使用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 -测试-例外- - java - 8. - html

#6


6  

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();

#7


1  

Using mockito, you can make the exception happen.

使用mockito,您可以使异常发生。

when(testingClassObj.testSomeMethod).thenThrow(new CustomException());

当(testingClassObj.testSomeMethod)。thenThrow(新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

在这里找到一个示例:assert exception junit

#8


-1  

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块中断言一个false条件。

#9


-1  

Assert by exception message:

维护异常消息:

    try {
        MyAgent.getNameByNode("d");
    } catch (Exception e) {
        Assert.assertEquals("Failed to fetch data.", e.getMessage());
    }