您的位置:首页 > 移动开发 > Android开发

Volley的unit test

2015-08-28 00:00 555 查看
android开发很多人会选择Volley作为网络框架,这是也是google推荐的,而开发过程中,除了编写代码,也需要编写unit test对编写的代码进行验证,为了能够在开发机器上面测试,而不用在真机上面进行测试,一般会选择Robolectric模拟android的相关实现。网上关于Volley的单元测试这方面的资料都不太全,经过一段时间的折腾摸索,终于搞掂了,现将方法放上来跟大家分享。

1)环境配置

android studio 1.2.2(有消息说google将会放弃eclipse,还是早点移过来吧)

volley 1.0.16

robolectric 3.0-rc3(网上很多是2.4的资料,但是2.4这个我怎么也调不过来,总是报Looper.getMainLooper()空指针异常)

junit 4.8.2

2)build.gradle(不适用于robolectric 2.4等版本)

dependencies {
compile 'com.mcxiaoke.volley:library:1.0.16'
testCompile 'junit:junit:4.8.2'
testCompile 'org.robolectric:robolectric:3.0-rc3'
}

3)测试代码

@RunWith(MyRobolectricTestRunner.class)
@Config(constants = BuildConfig.class)
public class parserTest{

@Test
public void testParseNetwork() throws Exception {

final CountDownLatch signal = new CountDownLatch(1);

StringRequest stringRequest = new StringRequest(Constants.GET_DATA_URL, new Response.Listener<String>() {
public void onResponse(String response) {

System.out.println("response = [" + response + "]");
signal.countDown();
}
}, new Response.ErrorListener(){
public void onErrorResponse(VolleyError error) {
signal.countDown();
Assert.fail();
}
});
MainActivity activity = Robolectric.setupActivity(MainActivity.class);

getTestQequestQueue(activity).add(xmlRequest);
signal.await(30, TimeUnit.SECONDS);
}
private RequestQueue getTestQequestQueue(Context context){
HttpStack stack = new HurlStack();
//        HttpStack stack = new HttpClientStack(new DefaultHttpClient());

Network network = new BasicNetwork(stack);

ResponseDelivery responseDelivery = new ExecutorDelivery(Executors.newSingleThreadExecutor());

RequestQueue queue = new RequestQueue(new NoCache(), network, 4, responseDelivery);

queue.start();
return queue;
}
}



4)代码解释

由于Volley接收到请求结果后,会将onResponse和onErrorResponse放在UIThread上运行,而Robolectric对UIThread模拟调用好像有问题,因此这里需要另外建立一个RequestQueue用新的responseDelivery代替原来的对UIThread的调用

CountDownLatch的作用则是让异步的Volley请求调用将结果显示在终端,signal.await()当前线程停止30s直到其他线程触发signal.countDown()才继续运行

版权声明:本文为博主原创文章,未经博主允许不得转载。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息