gpt4 book ai didi

android - Mockito 模拟 Android 上下文 PackageManager 异常

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:43:12 24 4
gpt4 key购买 nike

我开始使用 Mockito 进行 Android headless 单元测试。我要测试的部分是在依赖于 Context 的后端。我尝试模拟 Context 但在运行测试时我得到了 null。

这个例子中模拟的 Context 没有告诉我它是如何被模拟的: https://developer.android.com/training/testing/unit-testing/local-unit-tests.html#setup

上面链接中提到的示例 (https://github.com/googlesamples/android-testing/tree/master/unit/BasicSample) 没有说明如何模拟上下文的示例。

所以我有点迷路了。

我的 gradle 依赖项中有以下内容:

testCompile 'junit:junit:4.12'
androidTestCompile 'com.android.support.test:runner:0.4'
androidTestCompile 'com.android.support.test:rules:0.4'
androidTestCompile 'com.android.support:support-annotations:23.0.1'
testCompile 'org.mockito:mockito-core:1.10.19'
androidTestCompile('com.android.support.test:testing-support-lib:0.+')

代码 fragment :

@RunWith(MockitoJUnitRunner.class)
public static Test {
@Mock Context mContext;
RequestQueue mQueue;

@Test public void getCategories(){
final String SERVER = "http://{...}/categories";
mContext = mock(Context.class);
int size = 20;
when(mContext.getResources().getInteger(R.integer.cache_size)).thenReturn(size);
mQueue = VolleyUtil.newRequestQueue(mContext, null, size);

final Response.Listener<String> listener = new Response.Listener(){
//...
}

Response.ErrorListener error = new Response.ErrorListener(){
///...
}

mQueue.add(new JsonRequest(SERVER, listener, error);
}

VolleyUtil.newRequestQueue(final Context context, HttpStack stack, final int cacheMB){
final File cacheDir = new File(context.getCacheDir(), "volley");
if(stack == null) {
if(Build.VERSION.SDK_INT >= 9) {
stack = new HurlStack();
} else {
String userAgent = "volley/0";

try {
final String network = context.getPackageName();
final PackageInfo queue = context.getPackageManager().getPackageInfo(network, 0);
userAgent = network + "/" + queue.versionCode;
} catch (PackageManager.NameNotFoundException e) {
e.printStacktrace();
}

stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
}
}

final BasicNetwork network = new BasicNetwork((HttpStack)stack);
final RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir,diskCacheMB*1000000), network);
queue.start();
return queue;

我的空异常发生在:

final PackageInfo queue = context.getPackageManager().getPackageInfo(network, 0);

我应该模拟 PackageManager 还是 Application 实例?

最佳答案

因为您不是在 JUnit 上测试 android 资源,所以您也需要模拟它。例如:

PackageInfo pi = new PackgeInfo();
// modify it's value the way you desire
when(mContext.getPackageManager().getPackageInfo(network, 0)).thenReturn(pi);

然后继续单元测试。

关于android - Mockito 模拟 Android 上下文 PackageManager 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32872608/

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