kotlin 使用okhttp与junit4不能得到响应数据

vyswwuz2  于 2023-03-19  发布在  Kotlin
关注(0)|答案(1)|浏览(143)

在Kotlin项目中使用okhttp和Junit时,我发现了一个令人困惑问题
顺便说一下,这是我的环境:

  • 确定HTTP 4.9.0
  • junit 4.12
  • Kotlin1.4.20

下面是我简单代码:

class SingleFileDownloadTest {
    @org.junit.Test
    fun testDownloadSingleFile() {
        val client =  OkHttpClient()

        val request= Request.Builder().url("https://www.imooc.com/learn/1141").build()
        val call = client.newCall(request)

        //console outputs this log successfully
        
        // println(call.execute().body?.string())

        call.enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                e.printStackTrace()
            }

            override fun onResponse(call: Call, response: Response) {
                //this is wrong,I don't see the log in the console
                println(response.body?.string())
                println("resp success")
            }
        })

    }
}

我想是call.enqueue()中有错误还是其他原因导致了这个解决方案?
多谢帮忙
我想使用okhttp和junit4成功获取响应数据

efzxgjgh

efzxgjgh1#

我得到的答案是junit不支持多线程。
让线程休眠可以解决这个问题

class SingleFileDownloadTest {
    @org.junit.Test
    fun testDownloadSingleFile() {
        val client =  OkHttpClient()

        val request= Request.Builder().url("https://www.imooc.com/learn/1141").build()
        val call = client.newCall(request)

        //console outputs this log successfully
        
        // println(call.execute().body?.string())

        call.enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                e.printStackTrace()
            }

            override fun onResponse(call: Call, response: Response) {
                //this is wrong,I don't see the log in the console
                println(response.body?.string())
                println("resp success")
            }
        })

     Thread.sleep(10*1000)
    }
}

相关问题