首页 > 解决方案 > 出于测试目的注入和模拟第 3 方 ActivityResultContract

问题描述

我有一个Fragment。在这里面我开了Fragment一个 3rd 派对ActivityregisterForActivityResult(CropImageContract())

现在我想测试Fragment. 特别是我想验证是否Activity正确处理了第 3 方的结果。

由于在仪器测试期间我无法访问第 3 方Activity,我想注入和模拟CropImageContract()但我不知道如何。有什么想法或替代解决方案吗?

这是Fragment我要测试的:

class ProductDetailsFragment : Fragment() {
    private var mBinding: FragmentProductDetailsBinding? = null

    private val cropImageLauncher = registerForActivityResult(FakeCropImageContract()) { result ->
        if (result.isSuccessful) {
            // use the returned uri
            val uriContent = result.uriContent
        } else {
            // an error occurred
            val exception = result.error
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        mBinding = FragmentProductDetailsBinding.inflate(
            inflater,
            container,
            false
        )
        return mBinding!!.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        mBinding!!.contentProduct.productProductImageView.setOnClickListener { takePicture() }
    }

    private fun takePicture() {
        cropImageLauncher.launch()
    }
}

标签: android-fragmentsdependency-injectionmockingandroid-espresso

解决方案


推荐阅读