Mockito Mocking Android Context PackageManager Exception
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mockito Mocking Android Context PackageManager Exception相关的知识,希望对你有一定的参考价值。
我开始使用Mockito进行android无头单元测试。我要测试的部分是在后端,它依赖于Context。我尝试模拟上下文,但是当我运行测试时我得到null。
在这个例子中看到的模拟上下文并没有告诉我它是如何被嘲笑的: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.+')
代码片段:
@RunWith(MockitoJUnitRunner.cass)
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;
我的null异常发生在:
final PackageInfo queue = context.getPackageManager().getPackageInfo(network, 0);
我想模拟包管理器或应用程序实例?
答案
既然你没有在JUnit上测试android资源,你也需要模拟它。例如:
PackageInfo pi = new PackgeInfo();
// modify it's value the way you desire
when(mContext.getPackageManager().getPackageInfo(network, 0)).thenReturn(pi);
然后继续进行单元测试。
以上是关于Mockito Mocking Android Context PackageManager Exception的主要内容,如果未能解决你的问题,请参考以下文章
使用 Mockito 返回 Java 8 Optional Object 的 Mocking Object 返回 Empty Optional