Android CustomView Unit Testing

Prasoon Abhishek
2 min readOct 14, 2021

We all write custom Views and View Holders in our android apps. Sometimes these get complicated with lots of logical calculations and DTO related stuffs. It’s always better to Unit test these components, so that any change will not break the functionality.

Since this is a unit test, we don’t need any android environment for our test to run. We can simply mock our View and test it by attaching to an Activity.

Steps :

  1. Create a custom component.
  2. Add test dependencies
  3. Create test class and write tests

Step 1 —

  1. Create a custom component, here I am creating a simple component with a TextView.

2. Below is the layout Xml.

Step 2 —

  1. Add below dependencies

Note : Adding roboelectric dependency let’s us run the test inside test folder without having to run on any actual android emulator or device, if we don’t include roboelectric dependency we will have to move the test to androidTest folder and then it will be run on an emulator or actual device making the test slow.

Step 3 —

  1. Create a Test class in the test folder inside src.
  2. We will use ActivityScenario to create our view. ActivityScenario provides APIs to start and drive an Activity’s lifecycle state for testing. To know more about ActivityScenario visit —

https://developer.android.com/reference/androidx/test/core/app/ActivityScenario

3. Declare activityScenario as -

private var scenario: ActivityScenario<Activity>? = null

4. Create a setUp function and annotate it with @Before , this will run before every test case. Inside setUp function initialise scenario as -

scenario = ActivityScenario.launch(
Intent(ApplicationProvider.getApplicationContext(), MainActivity::class.java)
)

5. Create a tearDown function and annotate it with @After, this will run after every test case. Inside tearDown we need to close our scenario as -

scenario?.close()

6. Now we can write any test case as we want by using activities scenario. Here I will be writing a test case to test the text of our View as —

scenario?.moveToState(Lifecycle.State.CREATED)
scenario?.onActivity { activity ->
labeledTextInput = LabeledTextInput(activity)
Truth.assertThat(labeledTextInput?.getTvTitle()?.text).isEqualTo("Hi There")
}

For entire test class code refer below image :

Thanks.

--

--