Jak*_*ter 7 java testing mockito kotlin
我正在使用Kotlin并尝试在特定方法调用上引发Exception,但始终会收到以下错误
Checked exception is invalid for this method!
Invalid: exceptions.ServiceException
Run Code Online (Sandbox Code Playgroud)
这是测试
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")
}
Run Code Online (Sandbox Code Playgroud)
基本上,该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}")
}
}
}
Run Code Online (Sandbox Code Playgroud)
.doAnswer { throw ServiceException("Bad Request") }
Run Code Online (Sandbox Code Playgroud)
小智 5
就我而言,我使用的是引发已检查异常的底层 Java 客户端。我的 Kotlin 代码需要处理这些异常的一种变体,因此为了测试这个代码路径,我可以使用:
whenever(someObject.doesSomething(any()).then {
throw MyCheckedException("Error")
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1951 次 |
| 最近记录: |