Home > Software engineering >  assertThrows get error message and assert based on that
assertThrows get error message and assert based on that

Time:11-11

I have a custom runtime exception:

case class AEMAuthenticationException(
  message: String
) extends RuntimeException(message)

while writing test, I am using AssertThrows:

assertThrows[AEMAuthenticationException] {
      AEMUtils.validateAEMRequest[AEMFragment](
        status =  401,
        resBody = resBody
      )
    }

the above succeeds, however there are multiple Authentication exception that I would like to test. And I have distinguished them based on error message.

So my question is how can I have error message and assert based on that?

Something like below:

assertThrows[AEMAuthenticationException] {error => {
      AEMUtils.validateAEMRequest[AEMFragment](
        status =  401,
        resBody = resBody
      )
      assert(error.getMessage === "Expired Credentials")
     }
    }

CodePudding user response:

The ScalaTest documentation suggests intercept for examining a thrown exception:

val error = intercept[AEMAuthenticationException] {
      AEMUtils.validateAEMRequest[AEMFragment](
        status =  401,
        resBody = resBody
      )
    }
assert(error.getMessage === "Expired Credentials")
  • Related