我如何在Flutter中验证单个表单字段

时间:2020-02-12 14:35:38

标签: flutter

我有一个带有多个控件的表单,但分布在多个选项卡上。如果用户单击一个按钮,我希望为单个字段调用验证器功能。

1 个答案:

答案 0 :(得分:9)

要验证具有@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() ) ) ) } } } } } 类型的单个表单域创建密钥,请将该密钥分配给表单域并在密钥的当前状态上调用FormFieldState方法:

validate