我正在学习TDD,并且遇到以下情况。首先,我使测试emptyTitle_throwException
失败并通过。 validTitle_setTitleTextView
也是如此。
现在用于测试emptyMessage_throwException
,我使它失败然后通过,但是当通过时,它将导致测试validTitle_setTitleTextView
失败,因为basicDialogFragment.basicDialog.message
为空。
将行basicDialogFragment.basicDialog.message = message
添加到测试validTitle_setTitleTextView
将解决问题,但这是有效的方法,即使此行对我要测试的内容没有影响?
@Rule
@JvmField
val dialogTestRule: FragmentTestRule<*, BasicDialogFragment> =
FragmentTestRule.create<BasicDialogFragment>(
BasicDialogFragment::class.java,
false, false
)
val title = "Title"
val message = "Message"
val empty = ""
@Test(expected = RuntimeException::class)
fun emptyTitle_throwException() {
// Arrange
val basicDialogFragment = BasicDialogFragment()
basicDialogFragment.basicDialog.title = empty
// Act
dialogTestRule.launchFragment(basicDialogFragment)
}
@Test
fun validTitle_setTitleTextView() {
// Arrange
val basicDialogFragment = BasicDialogFragment()
basicDialogFragment.basicDialog.title = title
// basicDialogFragment.basicDialog.message = message <--- THIS WILL SOLVE THE PROBLEM
// Act
dialogTestRule.launchFragment(basicDialogFragment)
// Assert
onView(withId(R.id.titleTv)).check(matches(withText(title)))
}
@Test(expected = RuntimeException::class)
fun emptyMessage_throwException() {
// Arrange
val basicDialogFragment = BasicDialogFragment()
basicDialogFragment.basicDialog.title = title
basicDialogFragment.basicDialog.message = empty
// Act
dialogTestRule.launchFragment(basicDialogFragment)
}
在测试validTitle_setTitleTextView
中添加该行是合理的,因为它使此测试具有正确/完整的Arrange
。因为基于测试emptyMessage_throwException
,我假设当消息为空时,应该引发异常。
关于validTitle_setTitleTextView
失败的原因,这是另一个主题。测试很有可能按以下顺序执行:
((默认情况下,测试将按名称的字母顺序运行)
emptyMessage_throwException
测试执行后,empty
消息以某种方式没有清除,并导致validTitle_setTitleTextView
测试中出现问题。