方法调用在运行测试时会导致 ClassCastException



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

FragmentToTest extends ParentNotification extends来自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(){
    }

}

的错误消息

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,并通过您编写的源代码自己进行转换。

最新更新