在Kotlin与Mockito投掷例外



我正在使用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")
}

基本上getUserDataByNameAndRegion方法将调用makeRequest方法,并且通过此测试,我想验证该方法正在正确处理固态方法的结果。

原始方法看起来像

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

您可以尝试以下想法(摘自GitHub上的类似讨论(:

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

您可以使用以下内容:

`when`(someClassMocked.muFunction).thenThrow(SocketException())

在我的情况下,我使用的是一个基础Java客户端,该客户端抛出了例外。我的Kotlin代码需要处理这些异常的一个变体,因此,要测试此代码路径,我可以使用:

whenever(someObject.doesSomething(any()).then {
    throw MyCheckedException("Error")
}

kotlin不支持创建投票例外的方法。您可以在Java中定义makeRequest,也可以更改ServiceException以扩展RuntimeException

相关内容

  • 没有找到相关文章

最新更新