I'm using mockito in a junit test. How do you make an exception happen and then assert that it has (generic pseudo-code)
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Assert by exception message:
Make the exception happen like this:
Verify it has happened either by asserting that your test will throw such an exception:
Or by normal mock verification:
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).
Use Mockito's doThrow and then catch the desired exception to assert it was thrown later.
BDD Style Solution (Updated to Java 8)
Mockito alone is not the best solution for handling exceptions, use Mockito with Catch-Exception
Mockito + Catch-Exception + AssertJ
Sample code
Dependencies
Updated answer for 06/19/2015 (if you're using java 8)
Just use assertj
Using assertj-core-3.0.0 + Java 8 Lambdas
Reference: http://blog.codeleak.pl/2015/04/junit-testing-exceptions-with-java-8.html
Or if your exception is thrown from the constructor of a class: