浓咖啡测试失败 [英] Espresso test Fail

查看:81
本文介绍了浓咖啡测试失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Android上进行一些Espresso测试.测试失败,并显示以下错误:

I am doing some Espresso testing in Android. The test is failing with this error:

java.lang.ClassCastException: androidx.fragment.app.testing.FragmentScenario $ EmptyFragmentActivity 无法转换为com.stavro_xhardha.pockettreasure.MainActivity

java.lang.ClassCastException: androidx.fragment.app.testing.FragmentScenario$EmptyFragmentActivity cannot be cast to com.stavro_xhardha.pockettreasure.MainActivity

这是我的测试方法:

 @Test
    fun toolbarTitle_shouldContainCorrectInput() {
        val mockNavController = mock(NavController::class.java)
        val fragmentScenario = launchFragmentInContainer<SetupFragment>()
        fragmentScenario.onFragment {
           Navigation.setViewNavController(it.view!! , mockNavController)
        }
        onView(withId(R.id.toolbar)).check(matches(withText("Pick your country")))
    }

但是错误不是来自Test类,而是来自我的被测试的Fragment. 崩溃是在以下代码行中执行的:

But the error doesn't come from the Test class but from my Fragment under test. The crash is executed in this line of code:

override fun onStart() {
        super.onStart()
        (activity!! as MainActivity).supportActionBar?.hide() //here
    }

我没有得到的是,在没有测试的情况下正常运行应用程序时,我没有遇到任何错误.

What I don't get here is that I face no error when I run the app normally without test.

推荐答案

以下是完整答案.因此,让我们重复一下launchFragmentInContainer.所有这些功能都将获取给定的片段,并将其启动到内部的EmptyFragmentActivity类中,从而将片段放置在根视图容器中.因此,它应仅用于检查片段,而与片段的父活动无关.在您的情况下,您尝试将操作栏隐藏在要测试的片段内.但是在测试中,您的片段将不会在MainActivity中启动.因此,如果您只想检查片段,而不是(activity!! as MainActivity).supportActionBar?.hide(),则最好编写这样的内容:

Here is the full answer. So, let's repeat about launchFragmentInContainer. All that this functionality does it take the given fragment and launch it inside of an internal EmptyFragmentActivity class — placing the fragment inside of the root view container. So, it should be used to check fragment only, which doesn't depends from it's parent activity. In your case, you try to hide an action bar inside the fragment you're testing. But in test your fragment will not be launched in MainActivity. So if you want to check only the fragment, instead of (activity!! as MainActivity).supportActionBar?.hide() you'll better need to write something like this:

if(activity!! is MainActivity){
    activity?.supportActionBar?.hide()
}

或者您应该为MainActivity或片段的使用位置编写测试

Or you should write the test for your MainActivity or where you use your fragment

这篇关于浓咖啡测试失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆