无法监视Android类

我有一个像这样的简单的android类常量:

public class Consts extends BaseConstants {

    public static final String SCHEME = "http";

    // Tag used to cancel the request
    public static final String TAG_JSON = "json_obj_req";
}

其中没有其他内容,因此应易于模拟.我在测试用例中称其为:

Mockito.spy(Consts.class); …这是失败的.下面是测试用例文件:

public class ApplicationTest extends ActivityInstrumentationTestCase2<MainActivity> {

  MainActivity mActivity;

  public ApplicationTest() {
      super(MainActivity.class);
  }

  @Override
  protected void setUp() throws Exception {
      super.setUp();

      setActivityInitialTouchMode(false);

      mActivity = getActivity();
  }

  public void testUrlValid() {
      Mockito.spy(Consts.class);
  }

}

这是测试用例的logcat输出:

Running tests
Test running started
org.mockito.exceptions.base.MockitoException:
Cannot mock/spy class java.lang.Class
Mockito cannot mock/spy following:
- final classes
- anonymous classes
- primitive types

——-更新:

我想监视我的mainActivity类,但得到了同样的Mockito异常:这是我正在测试的类:

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;


public class MainActivity extends ListPageActivity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      if (savedInstanceState == null) {
          getFragmentManager().beginTransaction()
                .add(R.id.container, new SummaryFragment(),"SummaryFragment")
                .commit();
      }

      loadBrandSound();

     if (!isNetworkAvailable())
          showToast(getString(R.string.no_network));
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is   present.
      getMenuInflater().inflate(R.menu.menu_main, menu);
      return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
      // Handle action bar item clicks here. The action bar will
      // automatically handle clicks on the Home/Up button, so long
      // as you specify a parent activity in AndroidManifest.xml.
      int id = item.getItemId();

      //noinspection SimplifiableIfStatement
      if (id == R.id.action_settings) {
          return true;
      }

      return super.onOptionsItemSelected(item);
  }
}

这是我的简单测试用例:

import android.test.ActivityInstrumentationTestCase2;
import android.widget.Button;
import android.widget.EditText;

import org.mockito.Mockito;

public class ApplicationTest extends ActivityInstrumentationTestCase2<MainActivity> {

    MainActivity mActivity;
    private Button goBtn;
    private EditText et_query;
    private RecyclerListAdapter mAdapter;

    public ApplicationTest() {
        super(MainActivity.class);
    }

    @Override
    protected void setUp() throws Exception {
        super.setUp();

        setActivityInitialTouchMode(false);

        mActivity = getActivity();

        goBtn=(Button)mActivity.findViewById(
                R.id.btn_go);
        et_query = (EditText)mActivity.findViewById(R.id.et_query);
    }

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

    public void testPreconditions() {
        assertTrue(mActivity.isNetworkAvailable());
        isLayoutValid();
    }

    public void isLayoutValid(){
        assertNotNull(goBtn);
    }

    public void testSomething(){
        Mockito.spy(MainActivity.class);
    }

}

为什么它在间谍线上失败了?这是日志:

    Running tests
Test running started
org.mockito.exceptions.base.MockitoException:
Cannot mock/spy class java.lang.Class
Mockito cannot mock/spy following:
- final classes
- anonymous classes
- primitive types
at mypackage.ApplicationTest.testSomething(ApplicationTest.java:65)
at java.lang.reflect.Method.invokeNative(Native Method)
at android.test.InstrumentationTestCase.runMethod(InstrumentationTestCase.java:214)
at android.test.InstrumentationTestCase.runTest(InstrumentationTestCase.java:199)
at android.test.ActivityInstrumentationTestCase2.runTest(ActivityInstrumentationTestCase2.java:192)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:191)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:176)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:554)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1729)

Finish

解决方法:

与Mockito.mock(Class T clazz)不同,Mockito.spy(T instance)采用一个实例.但是,两者都返回一个实例.您正在寻找替换静态字段,而不是实例方法.

Mockito无法模拟静态成员或最终类,因为它主要通过创建匿名代理实现或子类来工作.子类不能覆盖静态方法或扩展最终类,因此Java编译器采用了跳过Mockito提供的任何实现的快捷方式. (对于静态最终常数inlined at compile time尤其如此.)

尽管PowerMockito可以重写被测系统代码以模拟最终和静态方法调用,但是它对字段没有帮助.附加级别的间接访问可能是更好的解决方案.

public class MyApplication extends Application {
  public boolean isUrlValid(String url) {
    return isUrlValid(url, Consts.SCHEME, Consts.TAG_JSON);
  }

  static boolean isUrlValid(String url, String scheme, String jsonTag) {
    // ...
  }
}

public class MyApplicationTest {
  @Test public void urlValidShouldWork() {
    assertTrue(MyApplication.isUrlValid(VALID_URL, "fakescheme", "faketag");
  }
}

或者,使Consts根据访问器方法(getScheme)而不是字段(scheme)进行操作.诸如ProGuard之类的工具通常可以内联简单的方法调用,因此在生产中不应太慢或冗长,并且您将有更多的机会替代测试中的实现.有关在测试中插入/注入模拟实现的更多技术,请参见see this SO question.

上一篇:Spring:无法将模拟注入到带有@Aspect注释的类中


下一篇:java-如何改善Guava Optional的Mockito默认行为?