问题描述
使用AndroidX时,不推荐使用InstrumentationRegistry。 documentation状态
不推荐使用此方法。在大多数情况下,应使用getApplicationContext()代替检测测试上下文。如果确实需要访问测试上下文以访问其资源,则建议改用getResourcesForApplication(String)。
但是,我找不到如何在测试中获取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
不是应用程序资产的一部分-它位于src/androidTest/assets
文件夹中,并打包到AppName-buildType-androidTest.apk
中(它不在AppName-buildType.apk
中,为此,知道包装名称)。
如何推断测试APK的软件包名称?是否可以避免在单元测试中对包名称字符串进行硬编码?我正在寻找一种与原始代码一样优雅的解决方案,但不使用不推荐使用的方法。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)