I'm writing some POJO tests for my Android code.
I want to run them locally with the JDK (not with Dalvik on the emulator) - for speed, JUnit 4, Mockito, and being able to run headless without a device - so I have a separate "Java" project in Eclipse.
If the method I'm testing happens to reference anything from the Android SDK, e.g. android.util.Log
, the test fails - this makes sense because android.jar
isn't in the classpath. To reproduce I have this test case:
public class FooTests {
@Test
public void testFoo() {
android.util.Log.d("x", "y");
}
}
If I add android.jar
explicitly to the test project's classpath, I get exceptions like
java.lang.RuntimeException: Stub!
at android.util.Log.d(Log.java:7)
at com.example.FooTests.testFoo(FooTests.java:39)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
...
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Is there a way to make the code work without mocking out every last bit of Android SDK dependency? Perhaps a mocked-out android.jar
already exists?
EDIT: For now I ended up wrapping classes like android.util.Log
and injecting them into the instances, for classic IOC-based testing. Scott's PowerMock suggestion is my next step when I'll need it.
LATER EDIT: Robolectric!
You write your local unit test class as a JUnit 4 test class. To do so, create a class that contains one or more test methods, usually in module-name/src/test/ . A test method begins with the @Test annotation and contains the code to exercise and verify a single aspect of the component that you want to test.
Eclipse. To run from Eclipse, from your Package Explorer locate your JUnit test, in whichever folder you have designated it to. Right-click, and move down to Run As JUnit Test. This will execute your test and open a new JUnit window if not already open.
JUnit is a “Unit Testing” framework for Java Applications which is already included by default in android studio. It is an automation framework for Unit as well as UI Testing. It contains annotations such as @Test, @Before, @After, etc.
Instrumentation Test Support Furthermore, because JUnit 5 is built on Java 8 from the ground up, its instrumentation tests will only run on devices running Android 8.0 (API 26) or newer.
I had the same problem. I wanted to test simple POJOs locally.
Specifically, my code wanted to use android.util.Base64.
What I ended up doing was to use the SDK to install the Android 4 sources, and copied the android.util.Base64 class to my project.
Surprisingly enough, this worked.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With