gpt4 book ai didi

android - InstrumentationRegistry.getContext() 替换示例

转载 作者:行者123 更新时间:2023-12-04 23:39:58 26 4
gpt4 key购买 nike

在 AndroidX 中, InstrumentationRegistry 现在已被弃用。 documentation状态

This method is deprecated. In most scenarios, getApplicationContext() should be used instead of the instrumentation test context. If you do need access to the test context for to access its resources, it is recommended to use getResourcesForApplication(String) instead.


但是,我找不到任何有关如何获取 PackageManager 实例的示例。在测试中调用 getResourcesForApplication以及应将哪个包名称提供给其字符串参数。
例如,这是当前有效的代码:
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import org.junit.Test;
import org.junit.runner.RunWith;

import java.io.IOException;
import java.io.InputStream;

import androidx.test.InstrumentationRegistry;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.ext.junit.runners.AndroidJUnit4;

import static org.junit.Assert.*;

@RunWith(AndroidJUnit4.class)
public class MyTest {

@Test
public void processImage() {
// load image from test assets
AssetManager am = InstrumentationRegistry.getContext().getAssets();
InputStream is = null;
Bitmap image = null;
try {
is = am.open("image.jpg");
image = BitmapFactory.decodeStream(is);
} catch (IOException e) {
e.printStackTrace();
} finally {
if ( is != null ) {
try {
is.close();
} catch (IOException ignored) { }
}
}

assertNotNull(image);

// do something with the image
}
}
现在,如何在不使用已弃用的 InstrumentationRegistry.getContext() 的情况下重写此测试?请记住 image.jpg不是应用程序 Assets 的一部分 - 它位于 src/androidTest/assets文件夹并打包到 AppName-buildType-androidTest.apk (它不存在于 AppName-buildType.apk 中,我知道它的包名)。
如何推导出测试APK的包名?是否可以在我的单元测试中避免硬编码包名称字符串?我正在寻找一种与原始代码一样优雅但不使用已弃用方法的解决方案。

最佳答案

我认为你应该简单地使用 InstrumentationRegistry.getInstrumentation().getContext().getAssets()而不是 InstrumentationRegistry.getContext().getAssets() .
它将使用你的测试上下文,所以你应该得到你的 Assets 。

关于android - InstrumentationRegistry.getContext() 替换示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63363262/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com