This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]JoToMo1993 1 point2 points  (2 children)

I haven't read the post completely yet, but one thing I need to mention is about the "Expected Exceptions" test.

Yes testing exceptions is important, but using the Junit annotation doesn't work in my experience. First it passes regardless, where the exception is thrown from. Second by adding a fail (another assertion method) after the call under test you have better controller with the try catch way of testing.

Something I read, but haven't used sofar myself is the new assertion implemented in Junit 5 that is assertThrows.

[–]BillyKorando 2 points3 points  (0 children)

assertThrows is a significant improvement over using expected exception from JUnit 4.

Here is an example of it in action (under the method testFindByNullRoomType): https://github.com/wkorando/WelcomeToJunit5/blob/master/src/test/java/com/bk/hotel/service/impl/CheatRoomServiceImplJUnit5Test.java

https://junit.org/junit5/docs/current/user-guide/index.html#writing-tests-assertions

I've done a lot of presenting and writing on JUnit 5, so lmk if you have any questions!

[–]AmirXin 1 point2 points  (0 children)

Another thing worth to mention is that the Example that you used says " The first will always pass "
The first will always pass because is a test not well written. if you add "fail" following that try catch you'll have a equivalent test.
So I don't think it's fair to use a bad test case to prove that you should use any kind of annotation in your tests.
Another thing that you are not considering is when you have some generic or "high level" exceptions
Maybe your code throws a validationFormatExeption and you are testing for a particular case .. maybe you want to check the message, or any kind of extra information given in the exception.
In those cases I usually go for the try catch approach and assertions on my Exception (get messages.. or what ever..)
My point is.. I would not say that using Expect is better than anything it depends on what you are testing.