How do you test exceptions? Here are some what I c...
# random
How do you test exceptions? Here are some what I can think of. If you have a better idea please comment. 1. Don’t test exceptions. (don’t laugh, someone actually told me that it is what they’re doing). 2. Test roughly. E.g. if you want to test for an argument being invalid, you just check whether it throws 
 . But don’t care about whether it is thrown at exactly the argument you make it invalid. 3. Have a unique 
 class for every case of exceptions. E.g. every arguments may have a corresponding exception for being invalid. Then you just test whether that specific exception is thrown. 4. Test for the API response. 5. Having a field in exception which contains the details information of the exception. 6. Check message.
I guess by "test exceptions" you mean "test codepaths leading to an exception". My answer (as almost always) is: It depends. If there's only one way to get a certain exception type, I only test for the class (2️⃣). AssertJ has nice shortcuts for the most common exception types. If there are multiple ways or if the exceptions gets turned into an API response, I check the message (6️⃣).
I practice a mixture of 2, 4 and 6
👍 1
If I don’t want something to change without me noticing, I test it. So I test for an exception of the type I care about being thrown (this isn’t necessarily, though it is normally, the concrete type), and I assert that the properties of the exception are as expected. The format of the message can generally be a unit test of the exception class, as it should be a product of the properties of the exception - you shouldn’t have to parse an exception’s message to get at data about what caused the exception. Given the following exception setup:
Copy code
open class HttpError constructor(val status: Int, message: String) : Exception("$status: $message")
open class ClientError(status: Int, message: String) : HttpError(status, message)
class NotFound(val uri: URI) : ClientError(404, "nothing found at $uri")
I would unit test `NotFound`:
Copy code
NotFound(URI("<>")).apply {
  message shouldBe "404: nothing found at <>"
  status shouldBe 404
  uri shouldBe URI("<>")
and when testing a method that I expect to throw it:
Copy code
val notFound = shouldThrow<NotFound> {
  // code that throws it
notFound.uri shouldBe URI("<>")