Mockito Mocking Android上下文包管理器异常
我从Mockito开始进行Android无头单元测试。我要测试的部分位于后端,它取决于Mockito Mocking Android上下文包管理器异常,android,unit-testing,mockito,Android,Unit Testing,Mockito,我从Mockito开始进行Android无头单元测试。我要测试的部分位于后端,它取决于上下文。我尝试模拟上下文,但运行测试时得到空值 本例中显示的模拟的上下文没有显示它是如何模拟的: 上面链接()中提到的示例没有关于如何模拟上下文的示例 所以我有点迷路了 我的gradle依赖项中有以下内容: testCompile 'junit:junit:4.12' androidTestCompile 'com.android.support.test:runner:0.4' androidTestCom
上下文。我尝试模拟上下文
,但运行测试时得到空值
本例中显示的模拟的上下文
没有显示它是如何模拟的:
上面链接()中提到的示例没有关于如何模拟上下文的示例
所以我有点迷路了
我的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.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;
我是要模拟PackageManager
还是模拟应用程序
实例?既然你没有在JUnit上测试android资源,你也需要模拟它。例如:
PackageInfo pi=newpackgeinfo();
//按照您的意愿修改其价值
当(mContext.getPackageManager().getPackageInfo(网络,0))。然后返回(pi);
然后继续单元测试。您找到问题的解决方案了吗?我面临着类似的问题。