I'm in the process of writing an endpoint and web layer integration test, but I stuck to test the 404 Error.
The Endpoint:
@PreAuthorize("hasPermission('admin.faq')")
override fun getHelpById(helpId: Long): ResponseEntity<HelpDto> {
return try {
val help = helpService.getHelp(helpId)
val helpDto = helpMapper.helpToHelpDto(help)
ResponseEntity.ok(helpDto)
} catch (exception: HelpNotFoundException) {
ResponseEntity.notFound().build()
}
}
The service
override fun getHelp(helpId: Long): Help {
val optionalHelp = helpRepository.findById(helpId)
if (optionalHelp.isEmpty) {
throw HelpNotFoundException(helpId)
}
return optionalHelp.get()
}
The test so far
@Test
fun requestGetHelpByIdWithWrongHelpIdExpect404() {
val uri = "/helps/{helpId}"
val headers = HttpHeaders()
headers.add("X-UserID", "1")
headers.add("X-Permissions", "admin.faq")
val request: HttpEntity<HttpHeaders> = HttpEntity(headers)
val helpId: Long = 1
val params = mapOf("helpId" to helpId)
val builder = UriComponentsBuilder.fromUriString(uri)
val uriWithParams = builder.buildAndExpand(params).toUri().toString()
Mockito.`when`(helpService.getHelp(helpId)).thenThrow(HelpNotFoundException::class.java)
val result = testRestTemplate.exchange(uriWithParams, HttpMethod.GET, request, HelpDto::class.java)
println(result.statusCode)
assert(result != null)
assert(result.statusCode == HttpStatus.NOT_FOUND)
}
With this test I tried to test the case if the helpId cannot be found. To simulate that I mocked the helpService and want the method .getHelp to throw the Exception "HelpNotFound" (I know that mocking isn't so common in Integration Tests, but I had no clue how to solve it without)
My problem:
As mentioned in the title, the call Mockito.`when`(helpService.getHelp(helpId)).thenThrow(HelpNotFoundException::class.java)
throws the following ecxeption
Checked exception is invalid for this method!
Invalid: online.minimuenchen.mmos.socialservice.exceptions.HelpNotFoundException
My guesses:
I asked a friend of mine which in pretty good with java, and he said I have to add "throws HelpNotFoundException()" to the Method Signature, but thats not necessary in kotlin right. So I thought maybe it would help to add the annotation "@Throws(HelpNotFoundException::class)".
Another guess of mine is that "HelpNotFoundException::class.java" should be something like "HelpNotFoundException()".
If I should send more Infos please say it.
My problem was that I put the annotation @Throws() just into the Service Impl and not into the Interface.