简体   繁体   中英

Testing textview displays text as HTML

I'm trying to test a textview in my fragment. In my UI, the textview displays a HTML text, by using HtmlCompat api, as shown below:

tvNoDeals.text = HtmlCompat.fromHtml(getString(R.string.no_deals), HtmlCompat.FROM_HTML_MODE_LEGACY)

My aim is to test this behavior via an android Test , by using Espresso . To do so I need to use a mocked context to get my string from strings.xml file. My question is, am I forced to mock context or there are other ways to check if the string matches?

class RetailDealsTest : RetailTest() {

    lateinit var context: Context

    @Before
    fun setup() {
        context = getInstrumentation().targetContext
    }

    @Test
    fun testNoDealsUi() {
        val retail = getRetail(totalDeals = 0)
        launchScenario(retail)
        onView(withId(R.id.lNoDeals))
            .check(matches(isDisplayed()))
        onView(withId(R.id.lDeals))
            .check(matches(not(isDisplayed())))
        onView(withId(R.id.tvNoDeals))
            .apply {
                check(
                    matches(
                        withText(
                            HtmlCompat.fromHtml(
                                context.getString(R.string.no_deals),
                                HtmlCompat.FROM_HTML_MODE_LEGACY
                            ).toString()
                        )
                    )
                )
            }
        Thread.sleep(10000)
    }

    private fun launchScenario(retail: Retail): FragmentScenario<RetailDealsFragment> {
        val fragmentArgs = Bundle().apply {
            putParcelable(Constants.RETAIL_ID, retail)
        }

        return launchFragmentInContainer<RetailDealsFragment>(
            fragmentArgs
        )
    }
}

To get the Context mocked you want to use

val context: Context = InstrumentationRegistry.getInstrumentation().targetContext

If you want the resources

var resources: Resources = InstrumentationRegistry.getInstrumentation().targetContext.resources
//Then find the string using
resources.strings(your_id)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM