Testing textview displays text as HTML

Issue

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

Solution

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)

Answered By – Skizo-ozᴉʞS

Leave a Comment