簡體   English   中英

如何從測試 class 獲取屬性? FragmentScenario,濃縮咖啡

[英]How to get access to a property from the test class? FragmentScenario, Espresso

我想檢查我的 editTextView 和屬性字段 (crime.title)。 我如何從測試 class 中獲取此字段? 那是我的測試 Class:

@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
        }
    }
}

片段 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
        )

    }

這是第 5 版 Big Nerd Ranch 指南中的任務之一。 他們建議使用 onFragment() function,但我不知道該怎么做。 “例如,您可以測試並驗證 CheckBox 和 EditText 是否已連接到您的片段並更新 Crime。通過刪除屬性上的私有可見性修飾符並使用 FragmentScenario.onFragment(…) function,您可以訪問a 犯罪並執行適當的斷言。”

我想是這樣的

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: 犯罪
之后它看起來像這樣:

  @Test
    fun updatesCrimeAfterTextChange() {
        onView(withId(R.id.crime_title)).perform(replaceText("expected text"))
        fragmentScenario.onFragment { fragment ->
            assertEquals("expected text", fragment.crime.title)
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM