java - JUnit:如何获取非 Activity 测试用例的上下文?

标签 java android junit

我正在为我的非 Activity 类编写一个测试类:

    public class SinglePhoto {

    public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
                                                         int reqWidth, int reqHeight) {

        // First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(res, resId, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeResource(res, resId, options);
    }

   //---...
}

在我的测试类中,我需要访问上下文,但我不知道该怎么做:

    public class SinglePhotoTest extends TestCase {

    public void testDecodeSampledBitmapFromResource() throws Exception {

        SinglePhoto sp = new SinglePhoto();

        Context testContext = ??!

        Bitmap bmp = sp.decodeSampledBitmapFromResource(testContext.getResources(), R.drawable.sample, 100, 100);

    }
}

你能帮我吗?

谢谢

最佳答案

不要扩展 TestCase,而是扩展 AndroidTestCase。并使用 getContext() 方法获取上下文。这是 AndroidTestCase 文档:http://developer.android.com/reference/android/test/AndroidTestCase.html

关于java - JUnit:如何获取非 Activity 测试用例的上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31774055/

相关文章:

android表格布局rowspan

android - 如何在对话框选择器中显示所选日期?

android - 方法 "join"和类 "DeepCollectionEquality"未定义

java - JUnit 5 jupiter 中使用两个参数的参数化测试

java - 如何在 Eclipse 中调试类似于常规 Java 程序的 JUnit 测试

java - 在 IntelliJ 中调试 Arquillian 测试

java - 为什么最后一个字符没有出现?

java - 根据独立谓词将集合流式传输并收集到多个结果中

java - 如何根据用户输入重新启动我的java程序?

java - AnyChart 折线图缩放