我正在 Android 中进行一些 Espresso 测试。测试失败并出现此错误:
java.lang.ClassCastException: androidx.fragment.app.testing.FragmentScenario$EmptyFragmentActivity 无法转换为 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")))
}
Run Code Online (Sandbox Code Playgroud)
但是错误不是来自 Test 类,而是来自我的 Fragment under test 。崩溃是在这行代码中执行的:
override fun onStart() {
super.onStart()
(activity!! as MainActivity).supportActionBar?.hide() //here
}
Run Code Online (Sandbox Code Playgroud)
我不明白的是,当我在没有测试的情况下正常运行应用程序时,我没有遇到任何错误。
android android-fragments android-testing android-navigation android-espresso
我打算用来FragmentScenario单独测试片段。在此片段中,我正在访问父活动以调用一些方法。为此,我正在使用CommonActivityOperations接口。我在此应用程序中使用导航架构组件。
interface CommonActivityOperations {
fun closeSearchBar()
fun navigateBackWithResult(resultFor: String, result: Bundle)
}
Run Code Online (Sandbox Code Playgroud)
当我尝试在我的设备上运行测试时,AttractionDestinationFragment出现以下错误。
java.lang.ClassCastException: androidx.fragment.app.testing.FragmentScenario$EmptyFragmentActivity cannot be cast to .interfaces.CommonActivityOperations
景点目的地片段
const val DESTINATION_DATA_EXTRA = "destination_data_result"
class AttractionDestinationFragment : BaseFragment(), ItemClickListener, ToolbarSearchChangeListener{
private lateinit var navigationController: NavController
private lateinit var defaultAttractionList: MutableList<AttractionDestinations>
private lateinit var attractionDestinationRecyclerViewAdapter: AttractionDestinationRecyclerViewAdapter
private val viewModel by lazy { getViewModel<AttractionDestinationViewModel>() }
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_attraction_destination, container, false)
}
override fun onViewCreated(view: View, …Run Code Online (Sandbox Code Playgroud)