我正在使用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}")
}
}
}
答案 0 :(得分:2)
Kotlin不支持creating methods that throw checked exceptions。您可以在Java中定义makeRequest
,也可以更改ServiceException
以扩展RuntimeException
。
答案 1 :(得分:0)
您可以尝试以下想法(取自类似的discussion on github):
.doAnswer { throw ServiceException("Bad Request") }
答案 2 :(得分:0)
您可以使用以下内容:
`when`(someClassMocked.muFunction).thenThrow(SocketException())
答案 3 :(得分:0)
就我而言,我使用的是引发检查异常的底层Java客户端。我的Kotlin代码需要处理这些异常的一种变体,因此要测试此代码路径,我可以使用:
whenever(someObject.doesSomething(any()).then {
throw MyCheckedException("Error")
}