Intro to Android

Best Practices

Simplify Your Architecture

As with most object oriented realms, attempt to simplify the architecture as much as possible. Do this by creating abstract or base objects or interfaces. This way you can test shared behavior in one place instead of several, which simplifies tests and reduces code duplication.

Mock/Stub Functionality

Often we want to ensure that a certain action was performed but not actually run the code. To do this, you create a test class which extends the class under test and override/mock out/track that a particular function was called.

For example, if you want a particular click to make an API call, there is no need to make the actual call (since this would be an integration level test anyway). You can use this strategy to track that the function that invokes the call has been called, but avoid making the actual call.

This is can also be helpful when an operation crashes the unit testing framework (e.g. specialty library that causes funky side effects), doesn't play nice, or is otherwise unnecessary to invoke directly.

Utility Functions

I create several utility classes to improve the readability of my code. These live in my test structure under the package support. We'll add these files in the next lab.

Centralize Test Constants

Android strongly encourages the use of abstracting string resources into one place over using hard-coded string constants. I like to follow a similar pattern and use a test constants class when you have lots of test data. This can be really helpful when creating a user with lots of fields to mock out a JSON response.

Don't Repeat Yourself (DRY)

If you find yourself writing something more than once, that's an excellent time to reassess. Luckily since you will have a large base of unit tests at your disposal as well as powerful IDE tools, the refactoring will have minimal impact on the rest of the system!

Robust Testing Strategy

Finally, you shouldn't rely solely on unit tests to ensure the proper behavior of your app. These tests, though quite useful, only give you a small window into your app and it's behavior. At minimum, you should include integration level tests and have some level of manual QA in the process to ensure your app is everything that you want it to be.

References