Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use android.test.mock MockContext?

I'm new to Android testing and I'm trying to create an ApplicationTestCase using a MockContext.

Here's my code and it occurs error(java.lang.NoClassDefFoundError: android/content/Context)

I'm appreciate you give me some examples.

package com.example.defaultmocktest.test;

import junit.framework.TestCase;
import android.test.mock.MockContext;
import android.widget.Toast;

public class DefaultTestCase extends TestCase {

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

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

    public void testSetDayAndWeekSetsCorrectPosition() {
        Toast.makeText(new MockContext(), "Mocking", Toast.LENGTH_LONG).show();
    }

}

Thanks

I Added full errors

java.lang.NoClassDefFoundError: android/content/Context
    at java.lang.Class.getDeclaredMethods0(Native Method)
    at java.lang.Class.privateGetDeclaredMethods(Class.java:2436)
    at java.lang.Class.getMethod0(Class.java:2679)
    at java.lang.Class.getMethod(Class.java:1605)
    at org.eclipse.jdt.internal.junit.runner.junit3.JUnit3TestLoader.getTest(JUnit3TestLoader.java:99)
    at org.eclipse.jdt.internal.junit.runner.junit3.JUnit3TestLoader.loadTests(JUnit3TestLoader.java:59)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:452)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.lang.ClassNotFoundException: android.content.Context
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
    ... 10 more
like image 953
YG.K Avatar asked Mar 10 '13 01:03

YG.K


1 Answers

I believe that the MockContext is really just a MockContext. It is meant to provide just enough functionality to run tests, but is not supposed to run real UI tasks.

From the docs at http://developer.android.com/reference/android/test/mock/MockContext.html

"All methods are non-functional and throw UnsupportedOperationException."

If you are running UI/Integration tests, I would take a look at http://developer.android.com/tools/testing/testing_ui.html

like image 58
Shellum Avatar answered Nov 05 '22 14:11

Shellum