在 Kotlin 中使用 Mockito 抛出异常

2022-09-02 21:38:09

我正在使用Kotlin,并试图在特定方法调用上抛出异常,但总是得到以下错误

Checked exception is invalid for this method!
Invalid: exceptions.ServiceException

这是测试

val client : IClient = Mockito.spy(Client(Cnf("https://:region.example.com", key)))


@Test(expected = ServiceException::class)
fun test400ResponseFrom() {
    val url = "https://example.com/example/user/v3/user/by-name/JACKAPPLE"

    Mockito.doThrow(ServiceException("Bad Request")).`when`(client).makeRequest(url ,riotkey)
    client.getUserDataByNameAndRegion("jackapple", "BR")
}

基本上,该方法将调用该方法,并且通过此测试,我想验证该方法是否正确处理了存根方法的结果。getUserDataByNameAndRegionmakeRequest

原始方法如下所示

@Throws(NotFoundException::class, ServiceException::class)
fun makeRequest(url: String, key : String) : String {
    val con = prepareConnection(url, key)
    val statusCode = con.responseCode
    when {
        (statusCode == 400) -> throw ServiceException("Bad Request")
        (statusCode == 401) -> throw ServiceException("Unauthorized")
        (statusCode == 403) -> throw ServiceException("Forbidden")
        (statusCode == 404) -> throw NotFoundException("Data not Found")
        (statusCode == 415) -> throw ServiceException("Unsupported Media Type")
        (statusCode == 429) -> throw ServiceException("Rate limit exceeded")
        (statusCode == 500) -> throw ServiceException("Internal Server Error")
        (statusCode == 502) -> throw ServiceException("Bad Gateway")
        (statusCode == 503) -> throw ServiceException("Service unavailable")
        (statusCode == 504) -> throw ServiceException("Gateway timeout")
        (statusCode == 200) -> {
            return getStringResponseFromConnection(con)
        }
        else -> {
            throw ServiceException("Respondend with Statuscode ${statusCode}")
        }
    }
}

答案 1

你可以尝试以下想法(摘自github上的类似讨论):

.doAnswer { throw ServiceException("Bad Request") }

答案 2

Kotlin 不支持创建引发已检查异常的方法。您可以在 Java 中定义,也可以更改为扩展 。makeRequestServiceExceptionRuntimeException