-1

Looking for a way to replaceText or typeText into a edit text embedded in a TextInputLayout.

I have tried a few things like this:

perform(ViewActions.typeTextIntoFocusedView("String")); 

but I always end up with this:

java.lang.RuntimeException: Action will not be performed because the target view does not match one or more of the following constraints:
(((is displayed on the screen to the user) and has focus on the screen to the user) and (supports input methods or is assignable from class: class android.widget.SearchView))

3 Answers3

1

You'll have to create a new ViewAction since Espresso doesn't have access to the EditText embedded inside the TextInputLayout. You can use something like this

class TextInputLayoutActions {
    class ReplaceTextAction(private val text: String): ViewAction {
        override fun getDescription(): String {
            return String.format(Locale.ROOT, "replace text(%s)", text)
        }

        override fun getConstraints(): Matcher<View> {
            return allOf(isDisplayed(), ViewMatchers.isAssignableFrom(TextInputLayout::class.java))
        }

        override fun perform(uiController: UiController?, view: View?) {
            (view as? TextInputLayout?)?.let {
                it.editText?.setText(text)
            }
        }

    }

    companion object {
        @JvmStatic
        fun replaceText(text: String): ViewAction {
            return actionWithAssertions(ReplaceTextAction(text))
        }
    }
}

and then use it like

<ViewInteraction>.perform(TextInputLayoutActions.replaceText(<text>)
Napster
  • 1,353
  • 1
  • 9
  • 11
0

I tried it this way If you have access to the activity you can use findviewById as well

 @Test
fun testSave() {
    val book = Book(
        title = "Machine Learning",
        author = "Mohammed Fahim khan",
        year = "2021", imageUrl = ""
    )
    val testViewModel = BookViewModel(FakeBookRepositoryIT())
    launchFragmentInHiltContainer<BookDetailsFragment>(factory = fragmentFactory) {
        viewModel = testViewModel
        binding.etTitle.editText?.setText(book?.title.toString())
        binding.etName.editText?.setText(book?.author.toString())
        binding.etYear.editText?.setText(book?.year.toString())

    }


    /*onView(withId(R.id.et_title)).perform(replaceText(book.title))
    onView(withId(R.id.et_name)).perform(replaceText(book.author))
    onView(withId(R.id.et_year)).perform(replaceText(book.year))*/
    onView(withId(R.id.btn_save)).perform(click())
    val list = testViewModel.bookList.getOrAwaitValue()
    assertThat(list).contains(book)
}
0

As simple as:

onView(withId(R.id.YOUR_INPUT)).perform(typeText("bla bla"))
Yasser AKBBACH
  • 539
  • 5
  • 7