【问题标题】:Method invocation cause ClassCastException when run a test运行测试时方法调用导致 ClassCastException
【发布时间】:2018-01-04 12:01:40
【问题描述】:

我正在尝试在一个扩展了一些父母的片段中运行一些测试...我的问题是我有一种方法正在对一个 Activity 类进行强制转换。

FragmentToTestextendsParentNotification那个extends来自ParentFragment

这是我在 ParentFragment 中的方法:

public Location getCurrentLocation(){
        return ((ParentLocationActivity) getActivity()).getCurrentLocation();
    }

然后,当我运行我的测试时,我得到了这个错误:

java.lang.RuntimeException: java.lang.ClassCastException: android.support.v4.app.FragmentActivity cannot be cast to com.myproject.activity.ParentLocationActivity

如果我返回,例如,什么都没有。我可以完美地运行测试。但是我需要用这种方法测试 y 片段。

我的问题是;是某种修复测试错误的方法还是某种方法可以从我的测试类中隐藏此方法或类似跳过此方法的方法??

请注意,此方法 (getCurrentLocation()) 在需要时可以在整个应用程序中正常工作。

提前致谢

这是我的测试课:

public class CreateOfferPresenterTest extends FragmentActivity {


    @Rule
    public FragmentTestRule<?, CreateOfferFragment> fragmentTestRule = FragmentTestRule.create(CreateOfferFragment.class);


    @Test
    public void setUp(){
    }

}

【问题讨论】:

  • ParentLocationActivity 是否扩展 FragmentActivity?
  • AppCompatActivity 的 ParentLocationActivity 扩展
  • @Nilu 是的,ParentLocationActivity 是 AppCompatActivity 的扩展
  • @Nilu 对不起,我以前不明白你。是的,我以两种方式扩展了测试用例,我得到了这个错误:Can't create handler inside thread that has not called Looper.prepare()
  • @Nilu 我已经更新了我的测试课程。如您所见,只有两行。您希望我在测试之前的哪个位置尝试您的最后一个建议?

标签: android unit-testing mockito powermock


【解决方案1】:

错误提示

java.lang.RuntimeException: java.lang.ClassCastException: android.support.v4.app.FragmentActivity 不能转换为 com.myproject.activity.ParentLocationActivity

告诉你你有一个android.support.v4.app.FragmentActivity 对象并且不能将它转换为com.myproject.activity.ParentLoationActivity。如果您打算向下转换,则需要确保 ParentLocationActivity 直接或传递地从 FragmentActivity 扩展。否则,您将需要实现一个方法,该方法将根据 FragmentActivity 的需要创建您的 ParentLocationActivity,并通过您编写的源代码自己进行转换。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多