我想检查我的editTextView和属性(crime.title)的字段。我如何从测试类中得到这个字段?这是我的测试类:
@RunWith(AndroidJUnit4::class)
class CrimeDetailFragmentTest {
private lateinit var fragmentScenario: FragmentScenario<CrimeDetailFragment>
@Before
fun setUp() {
fragmentScenario = launchFragment() }
@After
fun tearDown() {
fragmentScenario.close() }
@Test
fun updatesCrimeAfterTextChange() {
onView(withId(R.id.crime_title)).perform(replaceText("newText"))
fragmentScenario.onFragment { fragment ->
// Here I want to assertEquals crime.title and text from editTextView
}
}
}
还有一段我的代码来自Fragment Class:
class CrimeDetailFragment : Fragment() {
private var _binding: FragmentCrimeDetailBinding? = null
private val binding
get() = checkNotNull(_binding) { "Cannot access binding because it is null. Is the view visible?" }
private lateinit var crime: Crime
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
crime = Crime(
id = UUID.randomUUID(),
title = "",
date = Date(),
isSolved = false
)
}
这是《Big Nerd Ranch Guide, 5th Edition》中的任务之一。他们建议使用onFragment()函数,但我不知道该怎么做。例如,您可以测试并验证CheckBox和EditText连接到你的碎片并更新犯罪系统。通过移除属性的私有可见性修饰符,并使用onfragment(…)函数,您可以访问并执行适当的断言。">
我想大概是这样的
fragmentScenario.onFragment { fragment ->
val textFromView = fragment.findViewById<TextView>(R.id.text_id).text
Assert.assertEquals("expected text", textFromView)
}
我已经添加了这个依赖项:
debugImplementation "androidx.test:monitor:1.6.0">
没有这个依赖项FragmentScenario没有工作,测试加载无休止。
在这里删除了私有修饰符:
private lateinit var crime: crime
之后是这样的:
@Test
fun updatesCrimeAfterTextChange() {
onView(withId(R.id.crime_title)).perform(replaceText("expected text"))
fragmentScenario.onFragment { fragment ->
assertEquals("expected text", fragment.crime.title)
}
}