JUnit tests run on a local computer that does not have all of the Android source code, but only stub classes (described here ). These stub classes allow you to compile an Android application against them (because their API is identical to the real Android platform), but they do not contain any logic to make them "easy."
By default, when you try to call any of the stub methods, you get an exception. Something like that:
public Bundle() { throw new RuntimeException("Stub!"); }
this error-prone approach was used so that developers do not accidentally run their code against these stub classes, and then wondered why it does not work.
However, this behavior can be changed using this configuration in build.gradle :
android { ... testOptions { unitTests.returnDefaultValues = true } }
this causes the stub methods to return the default value instead of throwing exceptions.
This feature is probably enabled, so when you run the JUnit tests you don't get an exception, but the Bundle#getString() method just returns the default value (which is null ).
If you want to test code with dependencies on the Android platform, you must do the following:
- Avoid these dependencies (e.g. Mockito)
- Running tests with Robolectric
- Run test cases on your Android device.
In any case, unitTests.returnDefaultValues = true is a VERY DANGEROUS function that you use because it makes your tests unreliable: some test may pass because the default value was returned by the stub method, but the functionality does not work on a real device. his.
source share