Mockito“.thenThrow”抛出:"Checked exception is invalid for this method!"

Mockito ".thenThrow" throws: "Checked exception is invalid for this method!"

我正在编写端点和 Web 层集成测试,但我坚持测试 404 错误。

端点:

@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()
    }
}

服务

override fun getHelp(helpId: Long): Help {

    val optionalHelp = helpRepository.findById(helpId)

    if (optionalHelp.isEmpty) {
        throw HelpNotFoundException(helpId)
    }

    return optionalHelp.get()
}

到目前为止的测试

@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)
}

通过这个测试,我尝试测试找不到 helpId 的情况。为了模拟我模拟了 helpService 并希望方法 .getHelp 抛出异常“HelpNotFound”(我知道模拟在集成测试中并不常见,但我不知道如何解决它)

我的问题:

如标​​题所述,调用Mockito.`when`(helpService.getHelp(helpId)).thenThrow(HelpNotFoundException::class.java)抛出以下异常

Checked exception is invalid for this method!
Invalid: online.minimuenchen.mmos.socialservice.exceptions.HelpNotFoundException

我的猜测:

我问过我的一个朋友java,他说我必须在方法签名中添加“throws HelpNotFoundException()”,但这在 kotlin 中不是必需的,对吧。 所以我想也许添加注释“@Throws(HelpNotFoundException::class)”会有所帮助。

我的另一个猜测是“HelpNotFoundException::class.java”应该类似于“HelpNotFoundException()”。

如果我要发送更多信息,请说出来。

我的问题是我将注解 @Throws() 放入服务实现而不是接口。