Junit testing and Android dependencies

Patryk Poborca
AndroidPub
Published in
2 min readOct 15, 2015

Today’s article is going to be a quick blurb in regards to a common incorrect statement that

Oh wow, you have to be careful with your android dependencies, otherwise you won’t have POJO Viewmodels or Presenters

Repository for this article

POJO is an acronym for “Plain old Java Object” quite literally it means no non-java framework dependencies, so no android classes such as LatLng or SparseArray. Often we want to be able to have our VM or Presenter push strings that might be located in XML to the view. However we’re concerned that the dependency will stop us from being able to run our tests. Fortunately this is not the case, we can mock Resources in our VM and still have Junit tests.

A while back the Android package has been stubbed out for the purpose of Junit tests and classes are no longer final. This means that you can write mocks in order to utilize the class in you business logic. I have written a repository where a presenter after having a FAB clicked will push a message to the screen. In this past I would’ve thought that was the end of my Junit tests, but now that’s true!

With Mockito:

Without Mockito

Where this is our mocked Resources class

As you can see, in both cases I’m accomplishing the same thing, providing my Presenter with a mocked Resource class, and giving it a fake string. This string is obviously arbitrary and we’re done! That’s all it takes to mock an android dependency. You can throw in an override for getDrawable,or getDimensions.

How to run a JUnit test

Really quickly I will outline the steps since many people seem to skim over it. (It’s super easy!)

  1. Create a folder called “test” with a java directory:
app/src/test

2. Switch your build variant to UnitTests

3. Right click on your App directory and select “Run ‘All Tests’”

That’s all! Now each time you run your app simply switch your Run configuration from “app” to “Run all tests” and run your project, your tests will execute

Done.

Thanks for reading, if you enjoyed this or my other articles don’t forget to subscribe/favorite me here, or if you aren’t that into medium I have a Twitter as well

--

--