0

Regardless of what I do my check for when there is an exception isn't be handled. It's just being thrown in my test. I want to simulate an exception happening during the Db call and to return a 500 status code.

Given("given a db exception return Error 500") {
    val expectedException = "Exception while looking up in email opt DB"
    every { IDRepo.findById(any()) } throws RuntimeException(expectedException)
    When("process db exception") {
        val response = IDService.lookupIDValue(testEmail)
        then("response server error")
            response.statusCode shouldBe HttpStatus.INTERNAL_SERVER_ERROR
    }
}


fun lookupIDValue(email: String): ResponseEntity<String> {
        Failures.failsafeRun {
            IDRepo.findById(email)
        }
    val IDLookupResult = IDRepo.findById(email)
    return when {
        IDResult == Exception() -> {
            ResponseEntity("Server Error", HttpStatus.INTERNAL_SERVER_ERROR)
        }
        IDResult.isPresent -> {
            ResponseEntity(IDResult.get().optValue.toString(), HttpStatus.OK)
        }
        else -> {
            ResponseEntity(HttpStatus.NO_CONTENT)
        }
    }

}
Yazzz
  • 11
  • 6
  • `IDResult == Exception()` can never be true. The Exception class has no `equals()` implementation. Did you mean `IDResult is Exception`? – Tenfour04 Mar 14 '22 at 15:13
  • @Tenfour04 just noticed yup I need to change that. But my test still just throws the exception instead of having it be handled and return the response i want. – Yazzz Mar 14 '22 at 15:20

1 Answers1

0

I think, there are two issues with your code. The first one is IDResult == Exception() as @Tenfour04 said.

The second is mockk is throwing an exception without entering code block.

        IDResult == Exception() -> {
            ResponseEntity("Server Er... 

Without knowing about deeply your code, you should try the code below. Because you are testing the behaviour of IDRepo.findById(email) which should return a result of failure.

every { IDRepo.findById(any()) } returns Result.failure(RuntimeException(expectedException)))

Hope, it helps you.

ocos
  • 1,901
  • 1
  • 10
  • 12