Skip to content

Screen with Form and button action

Devrath edited this page Feb 27, 2024 · 2 revisions

Scenario

  • The screen contains the edit text and a button
  • User needs to enter some random text and then user clicks the button
  • On click of button in the on click action we update the test to a new value
  • We need to test that the updated values match the required value

Screen

Test

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

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

    /**
     * Matching the text by ID
     */
    @Test
    fun testDemo() {
        // <-------- ARRANGE -------->
        val textToBeTypedForTest = "Hello Everyone"
        val textToBeMatched = "Updated text"

        // <-------- ACT ------------>
        // Do the actions on the edittext
        onView(withId(R.id.edtInputFieldId))
            // Type the text
            .perform(typeText(textToBeTypedForTest))
            // Close the keyboard
            .perform(closeSoftKeyboard())

        // Do the actions on the button on the screen
        onView(withId(R.id.btnTextCheckId))
            // Click the button
            .perform(click())

        // <-------- ASSERT ----------->
        // Check the new text matches the required match
        onView(withId(R.id.edtInputFieldId)).check(matches(withText(textToBeMatched)))
    }

}

Code

FormScreenActivity.kt

class FormScreenActivity : AppCompatActivity() {

    private lateinit var binding: ActivityFormBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityFormBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.btnTextCheckId.setOnClickListener {
            binding.edtInputFieldId.setText("Updated text")
        }
    }

}

activity_form.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:gravity="center"
    android:padding="20dp"
    android:orientation="vertical"
    tools:context=".demos.MainActivity">

   <EditText
       android:id="@+id/edtInputFieldId"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:hint="Enter input"/>

    <Button
        android:id="@+id/btnTextCheckId"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Change text"/>

</LinearLayout>