【发布时间】:2018-03-14 01:15:37
【问题描述】:
这是测试方法:
它在发送 GET 请求后获取一个 URL 并返回一个 json。它是一个普通的函数,它位于包中,而不是类中的方法。以下扩展方法的情况相同。
fun getJson (url: String): String {
val connection = URL(url).openConnection() as HttpURLConnection
connection.requestMethod = "GET"
return connection.getResult()
}
这是扩展方法:
它将开始连接并从结果流中读取。
internal fun HttpURLConnection.getResult(charset: Charset = Charsets.UTF_8): String {
this.connect()
return this.inputStream.bufferedReader(charset).use { it.readText() }
}
这是测试用例:
我试着mock了这里即将使用的HttpURLConnection并调用原来的方法,然后只调用该方法并断言mock是否已设置为期望值。
class Spike {
@Test
fun test_getJson() {
val expectedResult = "{ok: true}"
val mockConnection = mock(HttpURLConnection::class.java)
Mockito.`when`(mockConnection.getResult()).thenReturn(expectedResult)
getJson("http://www.google.com")
assertEquals("GET", mockConnection.requestMethod)
assertEquals("http://www.google.com", mockConnection.url.host)
}
}
这是错误
java.lang.IllegalStateException: this.inputStream 在 my.spike.pack.http.UtilsKt.getResult(utils.kt:45)
就像模拟不工作一样。
如何在不改变getJson函数签名的情况下解决这个问题?
【问题讨论】:
-
感谢您的来信。现在更清楚了!那行不通:(
标签: unit-testing mocking kotlin mockito