Testing TextView line count with Robolectric

312 views Asked by At

I'm trying to write Robolectric test cases for line count in TextView, but I always get 1 as a line count whatever the length of the text is.
This is the test case I'm writing:

@Test
  fun test() {
    launch(TopicInfoTestActivity::class.java).use {
      it.onActivity { activity ->
        val descriptionTextView = getTopicDescriptionTextView(activity)
        assertThat(descriptionTextView?.lineCount).isEqualTo(5)
      }
    }
  }

Test result:

expected: 5
but was : 1

Another Test case:

@Test
  fun secondTest() {
    launchTopicActivityIntent().use {
      onView(withId(R.id.topic_description_text_view))
        .check(matches(lineCount(5)))
    }
  }

Here I'm using a custom matcher, here is its code:

private fun lineCount(lineCount: Int): TypeSafeMatcher<View> {
    return object : TypeSafeMatcher<View>() {
      var count = 0
      override fun matchesSafely(item: View): Boolean {
        count = (item as TextView).lineCount
        return item.lineCount == lineCount
      }

      override fun describeTo(description: Description) {
        description.appendText("isTextInLines: $lineCount Got: $count")
      }
    }
  }

Test result:

Expected: isTextInLines: 5 Got: 1

Any idea of how to test the line count with Robolectric?

0

There are 0 answers