MockitoException:无法模拟类com.example.example.test.MainActivity

时间:2013-10-16 15:27:50

标签: android unit-testing mockito android-testing

我尝试安装 Mockito 并收到错误消息。当我得到它时,我会回来添加我自己的答案。

对于真正的MainActivity及其派生的MockActivity,测试端都会发生这种情况。

它也发生在一个新的Android项目中,安卓版本为4.3,还有一个非常新的Eclipse。再加上Mockito 1.9.5。有问题吗,维护者?

测试用例很简单,使用ActivityUnitTestCase<MainActivity>

之前有没有人见过这种堆栈跟踪?

org.mockito.exceptions.base.MockitoException: Failed to mock class com.example.example.test.MockActivity

at com.example.example.test.SmartPhinsTest.test_mockito_mocks_activities(ExampleTest.java:39)

at java.lang.reflect.Method.invokeNative(Native Method)
at android.test.InstrumentationTestCase.runMethod(InstrumentationTestCase.java:214)
at android.test.InstrumentationTestCase.runTest(InstrumentationTestCase.java:199)

有人可能已经找到了测试框架标签吗?

(普通)代码片段是:

package com.example.example.test;

import java.io.File;

import android.app.Instrumentation;
import android.content.Context;
import android.content.Intent;
import android.test.ActivityUnitTestCase;

import com.example.example.MainActivity;

import static org.mockito.Mockito.*;

public class ActivityTests extends ActivityUnitTestCase<MainActivity> {
    public ActivityTests(Class<MainActivity> activityClass) {
        super(activityClass);
    }
    public ActivityTests() {
        super(MainActivity.class);
    }
    Activity activity;
    Context targetContext;
    Intent intent;

    @Override
    protected void setUp() throws Exception {
        targetContext = getInstrumentation().getTargetContext();
        intent = new Intent(targetContext, MainActivity.class);
        super.setUp();
        startActivity(intent, null, null);
        activity = getActivity();
    }                
    public void test_mockito_mocks_activities() {            
        Context context = activity.getApplicationContext();
        File cacheDir = context.getCacheDir();
        String path = cacheDir.getPath();
        System.setProperty("dexmaker.dexcache", path); // "/storage/sdpath");
        MainActivity mockActivity = mock(MainActivity.class);
    }
}

我还在android.permission.WRITE_EXTERNAL_STORAGE个文件中添加了AndroidManifest.xml。而且,尽管大多数示例使用ActivityInstrumentationTestCase2,但它拒绝为我工作 - 即使在另一个平台上的绿地项目中也是如此。

相当一致地给了我:

E/dalvikvm(3576): Could not find class 'android.app.LoaderManagerImpl', referenced from method MainActivity_Proxy.getLoaderManager
E/dalvikvm(3576): Could not find class 'android.app.Activity$NonConfigurationInstances', referenced from method MainActivity_Proxy.retainNonConfigurationInstances

1 个答案:

答案 0 :(得分:6)

在设置方法中输入:

// To solve some issue with Dexmaker
System.setProperty("dexmaker.dexcache", getContext().getCacheDir().getPath());