【发布时间】:2020-10-16 22:21:42
【问题描述】:
我正在编写一个类来对我的 ResponseHandler 类进行单元测试。我是否需要为我在 getErrorMessage 函数中考虑的每个可能的 HTTP 错误代码编写一个方法? 一个用于 400、401、403、404、503 等?
ResponseHandler.kt
enum class ErrorCodes(val code: Int) {
SocketTimeOut(-1),
NoConnection(0)
}
class ResponseHandler {
fun <T : Any> handleSuccess(data: T): Resource<T> {
return Resource.success(data)
}
fun <T : Any> handleException(e: Exception): Resource<T> {
return when (e) {
is HttpException -> Resource.error(getErrorMessage(e.code()), null)
is SocketTimeoutException -> Resource.error(getErrorMessage(ErrorCodes.SocketTimeOut.code), null)
is IOException -> Resource.error(getErrorMessage(ErrorCodes.NoConnection.code), null)
else -> Resource.error(getErrorMessage(Int.MAX_VALUE), null)
}
}
private fun getErrorMessage(code: Int): String {
return when (code) {
ErrorCodes.SocketTimeOut.code -> "Timeout"
ErrorCodes.NoConnection.code -> "No Connection"
HttpURLConnection.HTTP_BAD_REQUEST -> "Bad request"
HttpURLConnection.HTTP_UNAUTHORIZED -> "Unauthorized"
HttpURLConnection.HTTP_FORBIDDEN -> "Forbidden"
HttpURLConnection.HTTP_NOT_FOUND -> "Not found"
HttpURLConnection.HTTP_UNAVAILABLE -> "Service Unavailable"
else -> "Something went wrong"
}
}
}
ResponseHandlerTest.kt
@Test
fun `when exception is HttpException and code is 404 then return Not found error message`() {
val httpException = HttpException(Response.error<List<StylesData>>(HttpURLConnection.HTTP_NOT_FOUND, mock()))
val result = responseHandler.handleException<List<StylesData>>(httpException)
assertEquals("Not found", result.message)
}
@Test
fun `when exception is SocketTimeoutException then return Timeout error message`() {
val socketTimeoutException = SocketTimeoutException()
val result = responseHandler.handleException<List<StylesData>>(socketTimeoutException)
assertEquals("Timeout", result.message)
}
@Test
fun `when exception is IOException then return No connection error message`() {
val ioException = IOException()
val result = responseHandler.handleException<List<StylesData>>(ioException)
assertEquals("No Connection", result.message)
}
【问题讨论】:
标签: android unit-testing kotlin testing