Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Kotlin中模拟URL连接?_Kotlin - Fatal编程技术网

如何在Kotlin中模拟URL连接?

如何在Kotlin中模拟URL连接?,kotlin,Kotlin,我已经看过很多关于如何在Java中模拟连接的例子,但是没有看到任何关于如何在Kotlin中模拟连接的解释。我想以一段代码为例进行模拟: val url = URL("https://google.ca") val conn = url.openConnection() as HttpURLConnection with(conn) { //doStuff } conn.disconnect() 类似于这样的问题,但对于Kotlin: Kotlin和Java相互关联,因此您应该能够以提

我已经看过很多关于如何在Java中模拟连接的例子,但是没有看到任何关于如何在Kotlin中模拟连接的解释。我想以一段代码为例进行模拟:

val url = URL("https://google.ca")
val conn = url.openConnection() as HttpURLConnection

with(conn) {
    //doStuff
}
conn.disconnect()
类似于这样的问题,但对于Kotlin:

Kotlin和Java相互关联,因此您应该能够以提供的确切示例(从问题中)将其转换为Kotlin(或者不转换并直接调用Java):


值得注意的是,你可能应该考虑使用一个实际的嘲讽HTTP服务器来处理这个,而不是自己实现这个行为。

为什么一开始你就不应该嘲笑它。通过模拟,通过测试不会让您知道您的代码是否正确,是否可以与HTTP服务器正确交互。相反,使用类似于okhttp的模拟http服务器的东西,并使用真实代码连接到该服务器(通过注入模拟服务器的url而不是真实的url)
@Throws(Exception::class)
fun function() {
        val r = RuleEngineUtil()
        val u = PowerMockito.mock(URL::class.java)
        val url = "http://www.sdsgle.com"
        PowerMockito.whenNew(URL::class.java).withArguments(url).thenReturn(u)
        val huc = PowerMockito.mock(HttpURLConnection::class.java)
        PowerMockito.`when`(u.openConnection()).thenReturn(huc)
        PowerMockito.`when`(huc.getResponseCode()).thenReturn(200)
        assertTrue(r.isUrlAccessible(url))
}