Join Chiu-Ki Chan for an in-depth discussion in this video Testing with MVP: recipeNotFound(), part of Effective Android Testing for Mobile Developers.
- [Instructor] For our first test method, let's test a case when the recipe is not found. Create a new test method by starting with the annotation Test. Then public void recipeNotFound. To test the case when recipe is not found, what we are going to do is we are going to call the load recipe function and then specify that whenever somebody tries to load anything out of the store, we return a null object.
To specify that behavior of the store, we are going to use Mockito. Here is how you do it. Mockito.when store.getRecipe and then Mockito.anystring go to the end of the line, .thenreturn, null. Wow, that is not obvious at all, So let's walk through it. When we say Mockito when, and then return, it means that we are specifying the behavior when a function is called.
Here, we are saying that when the get recipe function is called on the recipe store, whatever the perimeter is, that's what we mean by Mockito dot any string, we are going to return null. We are doing that so that when call presenter dot load recipe, it can go to the store, and then return a null. Let's do that. In the next line, call presenter.loadRecipe It doesn't really matter what ID we give it, so we're going to pass in the dummy string, no_such_recipe.
The reason why this perimeter does not matter is because we have set up Mockito so that no matter what the ID is, get recipe will still return null recipe Next, what we want to do is that when the recipe is not found, meaning when it's null, we want to verify that the show recipe not found error function is called. Here is how we do that in Mockito. Mockito.verify and then we'll give it the object view, and then we want to say that it got called exactly one time.
So, Mockito.times(1) It just says that a function on the object view has been called once. We need to give it the function name. So, at the very end of the line, do .showRecipeNotFoundError Let's run the test. Go to the class name in line 13, and click on the green triangles on the gutter. Choose run.
It passed. And that's it. That's our very first MVP test. If you take a look at the function again, what we are doing is arrange at assert, meaning that in line 29, we are setting up the stage, we are setting up the fact that, if somebody calls the get recipe function, we are going to return a null object. Next line, line 30, is at. We are asking it to pretend to do something.
Afterwards, we are going to assert, meaning that we are verifying the behavior we expect. Next, we will add another test method. This time we are going to test the case when there is an exception.
- Why test?
- Local vs. on-device
- Code coverage
- UI testing
- Hermetic environment
- Dependency injection
- Testing with MVP