我正在尝试测试一些涉及 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
)没有主体。我不知道为什么会这样。
目前的想法:
- 我没有正确添加模拟响应正文
- 该文件以某种方式“打开”,因此它的长度始终为 0,即使它实际上不是空的。
编辑
我尝试MockWebServer
从测试中删除它并开始真正的下载,我的测试实际上通过了。MockResponse
所以,我认为我对 the和它的身体做错了什么。任何帮助将非常感激。