2

我正在尝试测试一些涉及 OkHttp3 的下载代码并且失败得很惨。目标:测试下载图像文件并验证它是否有效。平台:安卓。此代码正在生产中工作,但测试代码没有任何意义。

产品代码

class FileDownloaderImpl internal constructor(
    private val ioScheduler: Scheduler,
    private val logger: LoggingInterceptor,
    private val parser: ((String) -> HttpUrl)? // for testing only
) : FileDownloader {

    @Inject constructor(logger: LoggingInterceptor) : this(Schedulers.io(), logger, null)

    override fun downloadFile(url: String, destination: File): Single<File> {
        Logger.d(TAG, "downloadFile\nurl = $url\nfile = $destination")

        val client = OkHttpClient.Builder()
            .addInterceptor(logger)
            .build()

        val call = client.newCall(newRequest(url))
        return Single.fromCallable { call.execute() }
            .doOnDispose { call.cancel() }
            .subscribeOn(ioScheduler)
            .map { response ->
                Logger.d(TAG, "Successfully downloaded board: $response")
                return@map response.body()!!.use { body ->
                    Okio.buffer(Okio.sink(destination)).use { sink ->
                        sink.writeAll(body.source())
                    }
                    destination
                }
            }
    }

    /**
     * Creates the request, optionally parsing the URL into an [HttpUrl]. The primary (maybe only)
     * use-case for that is for wrapping the URL in a `MockWebServer`.
     */
    private fun newRequest(url: String): Request {
        val httpUrl = parser?.invoke(url)
        val builder = Request.Builder()
        httpUrl?.let { builder.url(it) } ?: builder.url(url)
        return builder.build()
    }
}

测试代码(JUnit5)

@ExtendWith(TempDirectory::class)
internal class FileDownloaderImplTest {

    private val mockWebServer = MockWebServer()
    private val logger = LoggingInterceptor(HttpLoggingInterceptor.Level.BODY) { msg -> println(msg) }
    private val fileDownloader = FileDownloaderImpl(Schedulers.trampoline(), logger) {
        mockWebServer.url("/$it")
    }

    @BeforeEach fun setup() {
        mockWebServer.start()
    }

    @AfterEach fun teardown() {
        mockWebServer.shutdown()
    }

    @Test fun downloadFile(@TempDir tempDirectory: Path) {
        // Given
        val res = javaClass.classLoader.getResource("green20.webp")
        val f = File(res.path)
        val buffer = Okio.buffer(Okio.source(f)).buffer()
        mockWebServer.enqueue(MockResponse().setBody(buffer))
        val destFile = tempDirectory.resolve("temp.webp").toFile()

        // Verify initial condition
        destFile.exists() shouldBe false

        // When
        fileDownloader.downloadFile("test.html", destFile)

            // Then
            .test()
            .assertValue { file ->
                file.exists() shouldBe true
                file.length() shouldEqualTo 66 // FAIL: always 0
                true
            }
    }
}

更多详情

“green20.webp”是一个存在于app/test/resources. 当我调试时,所有迹象都表明它存在。关于调试的主题,我在 prod 代码中有断点,看起来 Response 对象(大概是 a MockResponse)没有主体。我不知道为什么会这样。

目前的想法:

  1. 我没有正确添加模拟响应正文
  2. 该文件以某种方式“打开”,因此它的长度始终为 0,即使它实际上不是空的。

编辑

我尝试MockWebServer从测试中删除它并开始真正的下载,我的测试实际上通过了。MockResponse所以,我认为我对 the和它的身体做错了什么。任何帮助将非常感激。

4

2 回答 2

3

由于我不清楚的原因,Okio.buffer(Okio.source(file)).buffer()总是返回一个 empty Buffer。但是,以下方法有效:

mockWebServer.enqueue(MockResponse().setBody(Buffer().apply {
    writeAll(Okio.source(file))
}))

我现在正在做的是手动创建一个新缓冲区并将整个文件写入其中。现在我MockResponse有了一个真实的身体。

我仍然希望有人能解释为什么会这样......

于 2018-05-16T18:39:19.827 回答
2

buffer()on 方法BufferedSource不会将整个流读入该缓冲区以将其返回。相反,它只允许您访问它从文件中预加载的字节,这些字节将在下一次读取时返回。

这是将文件加载到缓冲区的代码:

val buffer = Buffer()
file.source().use {
  buffer.writeAll(it)
}
于 2018-05-17T02:33:08.330 回答