Skip to content

Finding the view by Id, Tag text displayed and matching to result

Devrath edited this page Feb 27, 2024 · 1 revision

Scenario

  • There is a text displayed on the screen
  • We need to check if the displayed text is Hello World!

Screen

Test

@RunWith(AndroidJUnit4::class)
@LargeTest
class MainActivityTest {

    // SUT
    @get:Rule
    val activityRule = ActivityScenarioRule(MainActivity::class.java)

    /**
     * Matching the text by ID
     */
    @Test
    fun testMatchById() {
        // ARRANGE
        val textToBeMatched = "Hello World!"
        // ACT AND ASSERT
        onView(withId(R.id.demoTextId)).check(matches(withText(textToBeMatched)))
    }

    /**
     * Matching by text
     */
    @Test
    fun testMatchByText() {
        // ARRANGE
        val textToBeMatched = "Hello World!"
        // ACT AND ASSERT
        onView(withText(textToBeMatched)).check(matches(isDisplayed()))
    }

    /**
     * Matching by tag
     */
    @Test
    fun testMatchByTag() {
        // ARRANGE
        val tagToBeFound = "demoTextTag"
        val textToBeMatched = "Hello World!"
        // ACT AND ASSERT
        onView(withTagValue(`is`(tagToBeFound))).check(matches(withText(textToBeMatched)))
    }


}

Code

MainActivity.kt

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".textmatch.MainActivity">

    <TextView
        android:id="@+id/demoTextId"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:tag="demoTextTag"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
Clone this wiki locally