我正在为我的非 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/