Test-Driven Development in Android

Jan 24 2023 · Kotlin 1.6, Android 12, AS Bumblebee 2021.1.1

Part 3: Test-Driven Development: UI Tests

19. Perform an Action

Episode complete

About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 18. Test for Text

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Transcript: 19. Perform an Action

There is one more behavior that we need to test and implement for our app which is that when the new jove button is clicked a new joke needs to be displayed. This final test will be a bit more complex so we will do it in two steps. First I am just going to copy and paste the longest code and I am going to explain to you what it does. Import all missing dependencies.

So first our new test is called onButtonClickNewJokeIsDisplayed. Then we create a new joke object with faker using an id and a lorem sentence. We have already done that.

Then here we create a Mockito answer, this allows us to create a more complex response. In our case we are queing jokes for each request because we want a new joke when the button is presed.

Then finally, we declare the repository mock and say that whenever we call the getJoke method in our repository we want to return our joke queue.

Great we can now finish our test. The code will be very similar to the code that we created in the past.

MainActivity.class.java

After our activity is launched we need to perform an action in our button, we need to click it. onView(withId(R.id.buttonNewJoke)).perform(click())

Import missing dependencies.

Finally we will verify that our TextView has a new Joke.

onView(withId(R.id.textJoke)).check(matches(withText(joke.joke)))

We re verifying that our joke tex view has a text that is equal to the joke that we just created.

Execute your test. We will see it fail after a few seconds.

And it failed.

Why? Because our textview does not have any new text it is still displaying the lorem ipsum text.

To fix that open the MainActivity.kt file and add this click listener to the bottom of onCreate()

binding.buttonNewJoke.setOnClickListener{

	viewModel.getJoke()

}

Go back and execute your test and see it pass.

Great our text is passing.

Now execute all of your tests to make sure they all still pass.

And they all still pass. Amazing.

So execute your app. Not your tests your app.

If you execute your app you will see that although our tests work as expected and they all pass the UI does not look so nice. We have a button at the top and the text is overlapping.

So we need to fix that.