Search code examples
androideclipseunit-testingjunitandroid-junit

Run vanilla JUnit tests on individual classes in an Android Eclipse JUnit project


I'm pulling my hair out trying to run a plain vanilla JUnit test on my Android project. I want to write a test for a POJO class that does not use any Android objects. In fact, I can't even get a test working that tests nothing!

I've read Google's "Testing Fundamentals" documentation, countless SO questions, and I think I've achieved a new height of stupidity, as I seem to have got less far than anyone in the history of Android.

My best guess at what I should be doing is this:

  1. Create a new android project. I have already developed my prototype application with activities, POJOs and everything else - it runs fine on my phone. "MyExample"
  2. In the Eclipse "Package Explorer" window, In the android project I want to test, in the "src" folder item, I right-click on the package item: "com.example.myexample", select "New" > "Other...",
  3. Then in the popup window, select "Android" > "Android Test Project"
  4. In "Project Name" text box, I enter "TestMyProject" and hit the "Next" button.
  5. Select the "An existing Android Project" radio button, select "MyExample", and click the "Finish" button.
  6. In "Package Explorer", expand "TestMyExample", right click on the package "com.example.myexample.test, select "New" > "JUnit Test Case".
  7. In that popup window, enter name "MyTestCase".

Then I enter the following in the java file:

package com.example.myexample.test;

import junit.framework.TestCase;

public class MyTestCase extends TestCase {

    public void testHelloWorld(){

        assertTrue("Hello World Error", false);

    }

}

Finally, I right-click the file in the package explorer, select "Run As" > "JUnit Test", then in the popup window, select "Use configuration specific settings", and select "Eclipse JUnit Launcher" and hit the "Ok" button.

I get this error in the console window:

Invalid layout of java.lang.String at value
#
# A fatal error has been detected by the Java Runtime Environment:
#
#  Internal Error (javaClasses.cpp:136), pid=5216, tid=2756
#  fatal error: Invalid layout of preloaded class

I seem to be getting a variety of "Invalid layout" errors depending on what procedure I use.

Please help!!


Solution

  • Unless there's a typo in your question, one possible problem is the way you are trying to run them.

    Select Run As -> Android JUnit test instead of just JUnit test. That's because these tests need to run on device, so the build is slightly more involved than for normal JUnit tests.

    I'm guessing you've already read the docs, but it's an easy thing to miss.