Join Chiu-Ki Chan for an in-depth discussion in this video Refactor: Toggle favorite, part of Effective Android Testing for Mobile Developers.
- [Instructor] Step five reacts to a user event. In other words, it goes from the view to the presenter. We will do that in the listener interface and have the presenter implement the listener interface. Go to the presenter and go to line 10. Add implements RecipeContract.Listener. Now, let's go to RecipeActivity. Here in step five in line 43 we have a ClickListener.
Inside we try to toggle the favorite states of our recipe but remember, we have hidden the recipe inside the presenter so we cannot do it directly here. What to do? What we can do is we can add a function to the presenter to toggle the favorite. At line 46, we will do presenter.toggleFavorite and then we will press alt enter to create this method.
We are going to create that inside the RecipePresenter. In toggleFavorites what we are going to do is copy and paste the thing from the RecipeActivity. Go to RecipeActivity, and then we are going to actually cut out lines 47 and 48, switch to the presenter. Inside the toggleFavorite function in line 44 paste it in. Magically the first line just compiles because favorite is a field and so is recipe, so inside the presenter we can still call favorites.toggle recipe.id.
However, how are we going to change the title view? Yes, we are going to use the view meaning the viewContract. The second line of the function toggleFavorite says that we are going to set the selector state of the title view but we cannot do that because we don't have control over the title view inside the presenter. What exactly are we trying to do? When we set the selector state of the title view, we are showing whether this recipe is a favorite.
Guess what? We have already defined that in our view, so we are going to call the function view.setFavorite. What are we going to pass as the parameter? We are going to pass in the result from the last line from line 34 because what happen is that we are going to call toggle on the favorite and then it will return the result meaning after toggling, flipping it between true and false, so in line 34 we can pass the result in right here and then we can delete line 36.
Let's go back to activity and look at that. We don't have any red squiggles anymore. Let's compile the app to make sure that it still works. Go to the dropdown and select app. Click on the green triangle. Let's click on fried tomatoes. We are going to click on the title and see if the star changes and yes, it get filled. If we go back and then click on fried tomatoes again, it is still selected.
So, horah, we have done all this refactoring and it looks like the app is still working.
- Why test?
- Local vs. on-device
- Code coverage
- UI testing
- Hermetic environment
- Dependency injection
- Testing with MVP