Join Chiu-Ki Chan for an in-depth discussion in this video RecipeApplication, part of Effective Android Testing for Mobile Developers.
- [Instructor] Now that we have "SharedPreferencesFavorites" and "InMemoryFavorites", how do we use one in the app, and the other in the test? We will use "Application" to help us. First, let's create the application. Go to "app", "src", "main", "java", right click on the package name, "New", "Java Class". We will call it "RecipeApplication". The package will have the prefix, ".injection".
The "RecipeApplication" will extend "Application". Inside this "Application", we are going to add a function called "getFavorites". This will return a latently-initialized "SharedPreferencesFavorites". This way, it is only going to be initialized when someone uses it. To do that, we will add a private variable, "private Favorites" and put "favorites", and set it to "null;" initially.
Then we will add the "getFavorites" function, "public_Favorites getFavorites()". When the variable favorites is null, we will need to initialize it, "if (favorites == null)", then "favorites = new SharedPreferencesFavorites". It need a context, which is "(this)", the application. At the end of this function, "return favorites". Now that we have created "RecipeApplication", we will need to declare it in "AndroidManifest.xml".
Press Command+Shift+All, and search for "AndroidManifest.xml". In line five, inside the application tag, add, "android:name=.injection.RecipeApplication.". Run the app. It still works. We haven't changed any of the logic yet, but we are just making sure that the whole thing still compiles. Next, let's go to "RecipeActivity".
Instead of creating "SharedPreferencesFavorites" here, we are going to ask the app to provide it. In line 35, we will need to retrieve the app. So, "RecipeApplication app = getApplication()". Press Alt+Enter to cast it. Then, in line 37, remove the "new SharedPreferences" part, and instead call "app.getFavorites()".
It is not happy, because "getFavorites return favorites", instead of "SharedPreferencesFavorites". Press Alt+Enter, and we'll change the variable favorites to type "favorites". Let's run the app. Again, nothing changed, but we're just trying to make sure that everything compiles. Next, we will create "TestRecipeApplication", which, instead of providing a "SharedPreferencesFavorites", it's going to provide "InMemoryFavorites".
- Why test?
- Local vs. on-device
- Code coverage
- UI testing
- Hermetic environment
- Dependency injection
- Testing with MVP