如何使用android.test.mockContext?

2022-09-02 14:07:48

我是Android测试的新手,我正在尝试使用MockContext创建一个AppplicationTestCase。

这是我的代码,它发生错误(java.lang.NoClassDefFoundError:android/content/Context)

我很感激你给我一些例子。

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();
    }

}

谢谢

我添加了完整错误

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

答案 1

我相信 MockContext 真的只是一个 MockContext。它旨在提供足够的功能来运行测试,但不应运行真正的 UI 任务。

来自 http://developer.android.com/reference/android/test/mock/MockContext.html

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

如果您正在运行UI /集成测试,我会看看 http://developer.android.com/tools/testing/testing_ui.html


答案 2