MockWebServer尚未完成

时间:2018-07-02 10:40:35

标签: mockwebserver

我像下面的代码一样使用MockWebServer。但是MockWebServer尚未完成。测试是无限进行的。我错过了什么?

结果: Jul 02, 2018 7:30:59 PM okhttp3.mockwebserver.MockWebServer$2 execute 정보: MockWebServer[49728] starting to accept connections

interface Webservice {
    @GET("users/{user}/missions")
    fun getMissions(@Path("user") user: String): Call<Missions>
}

class MockWebTest {

    private lateinit var webservice: Webservice

    @Before
    fun setUp() {
        val baseUrl = MyURL.API_DOMAIN
        val okHttpClient = OkHttpClient.Builder()
                .connectTimeout(2, TimeUnit.SECONDS)
                .readTimeout(2, TimeUnit.SECONDS)
                .writeTimeout(2, TimeUnit.SECONDS)
                .build()
        val retrofit = Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .build()

        webservice = retrofit.create(Webservice::class.java)
    }

    @Test
    fun test3() {
        val server = MockWebServer()
        server.start()

        val missionsJson = """
            {
                "message": "walk"
            }
        """.trimIndent()

        server.enqueue(MockResponse().setBody(missionsJson).throttleBody(1024, 1, TimeUnit.SECONDS))


        val call = webservice.getMissions("1")
        val entity = call.execute().body()!!

        assertEquals("walk", entity.message)

        val request1 = server.takeRequest()
        assertEquals("GET", request.method)
        assertEquals("/users/1/missions", request.path)

        server.shutdown()
    }
}

1 个答案:

答案 0 :(得分:1)

我检查了此仓库GithubBrowserSample Google示例。改造baseUrl需要由MockWebServer#url(String)

设置

不是我的网址,就像这样。

val retrofit = Retrofit.Builder()
        .baseUrl(server.url("/"))
        .client(okHttpClient)
        .addConverterFactory(GsonConverterFactory.create())
        .build()