Eclipse + Android + JUnit test references android.

2019-02-10 09:38发布

问题:

I have a custom timer that extends android.os.CountDownTimer. I have a test in the test project (standard Android/Eclipse project config) that tests the custom Timer. When I run this test, I get:

java.lang.NoClassDefFoundError: android/os/CountDownTimer
  at java.lang.ClassLoader.defineClass1(Native Method)
  at java.lang.ClassLoader.defineClass(ClassLoader.java:698)

You get the idea. Can I not run code that references android code code in junit test?

回答1:

You can't do that because it isn't possible to test Android's resources with JUnit without further instructions. You have to instrument your project first. This tutorials and the following describes this procedure very well:

http://mylifewithandroid.blogspot.com/2008/11/controlling-instrumentation.html
http://mylifewithandroid.blogspot.com/2008/11/junit-in-android.html

Here is an explained code snipplet of another test project: http://marakana.com/tutorials/android/junit-test-example.html

And here you can find the answer on Stack Overflow: https://stackoverflow.com/questions/522312/best-practices-for-unit-testing-android-apps