The main problem is that the Android Framework classes do not work very well outside the context of the Android OS, so any code that has dependencies on the Framework classes does not work in the usual JUnit environment, as you already found.
Your decision to try moving JUnit tests to a separate module will not work, because you cannot have a simple Java module depending on the Android module. Android Gradle modules do not act like Java modules, because Android builds are much more complex, and since the end result of assembling an Android module is APK or AAR, which other types of modules will not understand.
If you can port your simple Java classes and unit tests to a simple Java module and depend on Android modules, this would be the best approach that will get the most support from official functions in the IDE. It will also have an architectural advantage in that it saves these classes free of charge from Android abstractions, making them more portable and allowing the separation of business logic with a user interface or storage or other things more specific to the device.
If this is difficult for you, then many developers in your shoes come with Robolectric , which is a test harness that allows code depending on many parts of the Android Framework to run in the JUnit environment without an emulator or device. It is not officially supported by Google, but Google knows that it is widely used and is trying not just not to violate it.
source share