【问题标题】:Mockito ".thenThrow" throws: "Checked exception is invalid for this method!"Mockito“.thenThrow”抛出:“检查的异常对此方法无效!”
【发布时间】:2021-08-18 17:38:24
【问题描述】:

我正在编写端点和 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()”。

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

【问题讨论】:

  • @Jens 抱歉,我忘了添加服务。我在服务中抛出异常。

标签: spring kotlin controller mockito integration-testing


【解决方案1】:

我的问题是我把注解@Throws() 只是放到了Service Impl 中,而不是放到了Interface 中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多