Skip to content

Instantly share code, notes, and snippets.

@trietbui85
Last active July 29, 2020 13:41
Show Gist options
  • Save trietbui85/c879366105ca198d8d0f061a553626ba to your computer and use it in GitHub Desktop.
Save trietbui85/c879366105ca198d8d0f061a553626ba to your computer and use it in GitHub Desktop.
Unit test Android custom view with AndroidX Test and Robolectric
class CountView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0,
defStyleRes: Int = 0
) : LinearLayout(context, attrs, defStyleAttr, defStyleRes) {
private val buttonSubtract: Button
private val buttonAdd: Button
private val textViewCount: TextView
@VisibleForTesting
var countValue = 0
init {
inflate(context, R.layout.count_custom_view, this)
buttonSubtract = findViewById(R.id.buttonSubtract)
buttonAdd = findViewById(R.id.buttonAdd)
textViewCount = findViewById(R.id.textView)
buttonSubtract.setOnClickListener {
updateCount(countValue - 1)
}
buttonAdd.setOnClickListener {
updateCount(countValue + 1)
}
}
private fun updateCount(value: Int) {
countValue = value
textViewCount.text = countValue.toString()
}
fun reset() {
updateCount(0)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment