Android Espresso 3.6.x中captureToBitmap截图方法的使用问题
在Espresso 3.6.x中实现测试截图的方法
从Espresso 3.6.0版本开始,原同步返回Bitmap的captureToBitmap()方法被移除,替换为异步的CaptureToBitmapAction,需要通过实现BitmapReceiver接口来处理截图结果。以下是完整的实现步骤:
1. 实现带存储逻辑的BitmapReceiver
在onBitmapCaptured方法中完成Bitmap的存储操作,同时处理Bitmap为空的情况:
class BitmapReceiver(private val fileName: String) : ViewActions.BitmapReceiver { override fun onBitmapCaptured(bitmap: Bitmap?) { bitmap ?: return // 空Bitmap直接返回,避免空指针异常 // 调用原有存储方法,或实现标准文件写入逻辑 bitmap.writeToTestStorage(fileName) } } // 如果项目中没有现成的存储扩展方法,可参考以下实现: fun Bitmap.writeToTestStorage(fileName: String) { val outputStream = try { val testDir = File( InstrumentationRegistry.getInstrumentation().targetContext.externalCacheDir, "test_screenshots" ) if (!testDir.exists()) testDir.mkdirs() FileOutputStream(File(testDir, "$fileName.png")) } catch (e: IOException) { throw RuntimeException("创建截图文件失败", e) } compress(Bitmap.CompressFormat.PNG, 100, outputStream) outputStream.flush() outputStream.close() }
2. 执行截图操作
通过CaptureToBitmapAction将自定义的Receiver传入,触发截图:
val screenshotFileName = "${javaClass.simpleName}_${nameRule.methodName}-open" val receiver = BitmapReceiver(screenshotFileName) onView(isRoot()).perform(CaptureToBitmapAction(receiver))
3. 处理异步依赖(可选)
如果后续测试逻辑依赖截图完成,可通过CountDownLatch实现同步等待:
class CountDownBitmapReceiver(private val fileName: String) : ViewActions.BitmapReceiver { private val latch = CountDownLatch(1) override fun onBitmapCaptured(bitmap: Bitmap?) { bitmap?.writeToTestStorage(fileName) latch.countDown() } fun awaitCapture() { try { // 设置5秒超时,避免无限等待 if (!latch.await(5, TimeUnit.SECONDS)) { throw RuntimeException("截图超时未完成") } } catch (e: InterruptedException) { Thread.currentThread().interrupt() throw RuntimeException("截图等待被中断", e) } } } // 使用方式: val receiver = CountDownBitmapReceiver(screenshotFileName) onView(isRoot()).perform(CaptureToBitmapAction(receiver)) receiver.awaitCapture() // 后续执行依赖截图完成的测试逻辑
内容的提问来源于stack exchange,提问作者hannes ach
相关产品推荐
相关产品推荐

