我正在使用导航组件,我试图测试我的 Fragment
与工具测试。该片段有一个自定义工具栏,初始化为 onViewCreated
方法的扩展函数。
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
tbBlack.init()
}
fun androidx.appcompat.widget.Toolbar.init(
menuId: Int? = null
) {
title = ""
menuId?.let {
inflateMenu(it)
}
findNavController().let {
it.graph.let { graph ->
val configuration = AppBarConfiguration(graph)
setupWithNavController(it, configuration)
}
}
}
在我的仪器测试中,在初始化场景的过程中,由于一个叫 "D "的方法,测试崩溃了。null
导航控制器上的图形。
在测试中模拟了导航控制器,也模拟了下面这样的图形。
@RunWith(AndroidJUnit4::class)
class LoginFragmentTest {
@Test
fun testEmptyFields() {
val mockNavController = mock(NavController::class.java)
val mockGraph = mock(NavGraph::class.java)
mockNavController.graph = mockGraph
val scenario = launchFragmentInContainer(themeResId = R.style.AppTheme) {
LoginFragment().also { fragment ->
// In addition to returning a new instance of our Fragment,
// get a callback whenever the fragment’s view is created
// or destroyed so that we can set the mock NavController
fragment.viewLifecycleOwnerLiveData.observeForever { viewLifecycleOwner ->
if (viewLifecycleOwner != null) {
// The fragment’s view has just been created
Navigation.setViewNavController(fragment.requireView(), mockNavController)
}
}
}
}
scenario.onFragment {
it.run {
val viewsIds =
listOf(R.id.etEmailAddress, R.id.etPassword)
for (viewId in viewsIds) {
onView(ViewMatchers.withId(viewId))
.perform(ViewActions.replaceText(""))
Thread.sleep(500)
onView(ViewMatchers.withId(R.id.btLogin)).check(
ViewAssertions.matches(
CoreMatchers.not(
ViewMatchers.isEnabled()
)
)
)
}
}
}
}
}
我在模拟navController的过程中是否遗漏了什么?
我通过使用新的 TestNavHostController
由 androidx导航测试库
基本上,这样做。
dependencies {
def nav_version = "2.3.0-alpha06"
androidTestImplementation "androidx.navigation:navigation-testing:$nav_version"
}
TestNavHostController
在你的androidTest中。 // Create a TestNavHostController
val navController = TestNavHostController(
ApplicationProvider.getApplicationContext())
val fragmentArgs = Bundle().apply {
putParcelable(Constants.RETAIL_CLICK_SOURCE_ID, RetailDetailsClicked.Source.LIST)
putParcelable(Constants.RETAIL_ID, retail)
}
navController.setGraph(R.navigation.retail_details_graph)
launchFragmentInContainer(
fragmentArgs, R.style.AppTheme
) {
RetailDetailsFragment().also { fragment ->
// In addition to returning a new instance of our Fragment,
// get a callback whenever the fragment’s view is created
// or destroyed so that we can set the mock NavController
fragment.viewLifecycleOwnerLiveData.observeForever { viewLifecycleOwner ->
if (viewLifecycleOwner != null) {
// The fragment’s view has just been created
Navigation.setViewNavController(fragment.requireView(), navController)
}
}
}
}
就是这样!