【问题标题】:How to use intent when testing Android classes?测试Android类时如何使用intent?
【发布时间】:2011-06-24 06:00:48
【问题描述】:

这是一些示例代码,它似乎对我不起作用。

public class CropImageTest extends ActivityInstrumentationTestCase2<CropImage> {

    private Instrumentation mInstrumentation;
    private CropImage mActivity;
    private String filename = "/mnt/sdcard/DCIM/Camera/2011-05-12 09.22.56.jpg";
    private int aspectX = 1;
    private int aspectY = 1;
    private boolean scale = true;

    public CropImageTest() {
        super("hk.com.novare.android.cropimage", CropImage.class);
    }

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        this.mInstrumentation = getInstrumentation();
        Intent i = new Intent(mInstrumentation.getContext(), CropImage.class);

        i.putExtra("image-path", filename);
        i.putExtra("aspectY", aspectY);
        i.putExtra("aspectX", aspectX);
        i.putExtra("scale", scale);
        setActivityIntent(i);
        mActivity = this.getActivity();  
    }

    public void testExtras() {
        String str = "";
        str = mActivity.getIntent().getStringExtra("image-path");
        assertEquals(filename, str);
    }
}

遇到错误:

无法解析以下活动:Intent(有 Extras)

我的清单:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          android:versionCode="1"
          android:versionName="1.0"
          package="hk.com.novare.android.cropimage.tests">

    <uses-sdk android:minSdkVersion="8"/>
    <instrumentation
            android:targetPackage="hk.com.novare.android.cropimage"
            android:name="android.test.InstrumentationTestRunner"/>
    <application
            android:icon="@drawable/icon"
            android:label="@string/app_name">
        <uses-library android:name="android.test.runner"/>
    </application>
</manifest>

即使我将构造函数 -> super 的字符串(一个包)设置为与我在此测试项目的 manifest.xml 中指定的字符串相同,我也遇到了上述错误。 请帮帮我。

【问题讨论】:

    标签: android testing android-intent


    【解决方案1】:

    我认为你需要做的就是使用

    Intent i = new Intent();
    

    例如,请参阅this thread 上的答案。

    【讨论】:

    • 我以前做过这个,但它似乎不起作用,我有同样的错误“无法解决活动:意图 {flg=0x10000000 cmp=hk.com.novare. android.cropimage/.CropImage(有附加功能)}"
    • 愚蠢的问题,我认为,给定包名称,但 CropImage 是 hk.com.novare.android.cropimage 清单中列出的活动吗?
    • 一个被遗忘的问题,应该选择最接近的一个,但是谢谢! :D
    【解决方案2】:

    在创建意图时,您将传递 getInstrumentation().getContext() 这是测试应用的上下文。

    你想要的是getInstrumentation().getTargetContext(),它是目标应用程序的上下文。

    【讨论】:

      【解决方案3】:

      在构造 Intent 时,我认为您想调用 getActivity() 而不是 mInstrumentation.getContext()。我假设 CropImage 类实际上是在被测包中,而不是测试包中。

      【讨论】:

      • 是的,但它是应该获取和处理额外内容的那个,所以它没有意义。并且正如文档所示,您不能在 setActivityIntent() 之前调用 getActivity() 方法! :((
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多