java.lang.NoClassDefFoundError:android and junit test

I saw that I'm not the only one having this problem but I don't find a correct answer. I have an android project that I want to test. I create a junit test class for each class of my project. My problem is when I run my test, I have the following error :

java.lang.NoClassDefFoundError: android/content/Context

This is my class test :

public class DevicesBDDTest extends TestCase {

    DevicesBDD bdd;

    /**
     * @throws java.lang.Exception
     */
    protected static void setUpBeforeClass() throws Exception {
    }

    /**
     * @throws java.lang.Exception
     */
    protected static void tearDownAfterClass() throws Exception {
    }

    protected void setUp() throws Exception {
        super.setUp();
        Context ctx = mock(Context.class);
        final MaBaseSQLiteInterface mockMaBaseSQLite = mock(MaBaseSQLiteInterface.class);
        bdd = new DevicesBDD(ctx){
            @Override
            public MaBaseSQLiteInterface createMaBaseSQlite(Context context) {
                return mockMaBaseSQLite;
            }
        };
    }


    protected void tearDown() throws Exception {
        super.tearDown();
    }

    public void test() {
        assertEquals(1, 1);
    }
}

My class DevicesBDD has needs an object Context, therefore I create a mock (with mockito). I tried with a object MockContext too, but it's doesn't work.

This is my Java Build Path :

  • mockito-all-1.9.5.jar
  • Android 2.1 -> android.jar
  • Android Dependencies -> annotations.jar
  • Junit 3 -> junit.jar

Not sure if I had the same problem as you but I am using gradle and for some reason the tests just wouldn't run anymore, with the same error as you had. I tried cleaning and rebuilding but to no avail. After hours of frustration and trying to find an answer I came across the simple solution in a GitHub thread:

I resolved this issue by removing the .gradle folder in my project and rebuilding the project.

(thanks to vpetrov)


You can run ./gradlew clean test in the terminal.


Fixed the issue by following these steps --

1.Open module level build.gradle file, go to dependencies, go to this line --

testImplementation 'junit:junit:4.12'

2.Change the junit version to anything else below it (like 4.10)

testImplementation 'junit:junit:4.10'

3.Sync project

4.The issue fixed at this point in my case

5.Set the junit version back to what it was before (4.12 in my case) if you want

testImplementation 'junit:junit:4.12'

6.Sync project

Changing the junit version and syncing project worked in my case.