Android单元测试之对Activity的测试示例

Android单元测试之对Activity的测试示例,第1张

概述上一篇文章已经介绍了单元测试的作用和简单示例,如果不了解的读者可以先阅读上一篇Android单元测试-作用以及简单示例。 

上一篇文章已经介绍了单元测试的作用和简单示例,如果不了解的读者可以先阅读上一篇Android单元测试-作用以及简单示例。 

这篇文章主要介绍常见的Activity中的测试。

对Acitivity的测试

对于Activity,我们大致有两种测试需求:

1、在Activity正常启动后,查看界面布局是否正确,包括VIEw的点击事件等是否正确。

2、需要在Activity启动前完成各种数据的部署,然后查看Activity的效果。

对于这两种需求,笔者分别做了两个示例解说:

1、检测一个布局中的button和TextVIEw是否正确。

2、从网络动态获取String到Activity界面显示,并且这个图片的URL是由Intent传递过来的。

环境部署

首先要导入expresso-core的包,如下:

dependencIEs {  // Other dependencIEs ...  androIDTestCompile 'com.androID.support.test.espresso:espresso-core:2.2.2'}

当然在目前的项目架构中一般已经自动导入了这个包,所以不需要自己导入,笔者项目中自动导入的包如下如下:

dependencIEs {  compile filetree(include: ['*.jar'],dir: 'libs')  androIDTestCompile('com.androID.support.test.espresso:espresso-core:2.2.2',{    exclude group: 'com.androID.support',module: 'support-annotations'  })  compile 'com.androID.support:appcompat-v7:26.0.0-Alpha1'  compile 'com.androID.support.constraint:constraint-layout:1.0.2'  testCompile 'junit:junit:4.12'}

项目结构如下:

布局VIEw的测试:

package com.example.xujiajia_sx.myexpressotest;import androID.app.Activity;import androID.os.Bundle;import androID.support.annotation.Nullable;import androID.vIEw.VIEw;import androID.Widget.button;import androID.Widget.TextVIEw;/** * Created by xujiajia_sx on 2017/8/14. */public class SimpleVIEwActivity extends Activity{  private TextVIEw tv;  private button btn;  @OverrIDe  protected voID onCreate(@Nullable Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentVIEw(R.layout.act_simple_vIEw);    initVIEw();  }  private voID initVIEw() {    tv=findVIEwByID(R.ID.tv_simple_vIEw);    btn=findVIEwByID(R.ID.btn_simple_vIEw);    tv.setText("111");    btn.setText("222");    btn.setonClickListener(new VIEw.OnClickListener() {      @OverrIDe      public voID onClick(VIEw vIEw) {        tv.setText("777");      }    });  }}
<?xml version="1.0" enCoding="utf-8"?><linearLayout xmlns:androID="http://schemas.androID.com/apk/res/androID"  androID:layout_wIDth="match_parent"  androID:layout_height="match_parent"  androID:orIEntation="vertical">  <TextVIEw    androID:ID="@+ID/tv_simple_vIEw"    androID:layout_wIDth="wrap_content"    androID:layout_height="wrap_content"     />  <button    androID:ID="@+ID/btn_simple_vIEw"    androID:layout_wIDth="wrap_content"    androID:layout_height="wrap_content"    /></linearLayout>
package com.example.xujiajia_sx.myexpressotest;import androID.support.test.rule.ActivityTestRule;import org.junit.Rule;import org.junit.Test;import static androID.support.test.espresso.Espresso.onVIEw;import static androID.support.test.espresso.action.VIEwActions.click;import static androID.support.test.espresso.assertion.VIEwAssertions.matches;import static androID.support.test.espresso.matcher.VIEwMatchers.withID;import static androID.support.test.espresso.matcher.VIEwMatchers.withText;/** * Created by xujiajia_sx on 2017/8/14. */public class SimpleVIEwTest {  @Rule  public ActivityTestRule<SimpleVIEwActivity> mActivityTestRule =      new ActivityTestRule<SimpleVIEwActivity>(SimpleVIEwActivity.class);  @Test  public voID textVIEwtest() throws Exception {    onVIEw(withID(R.ID.tv_simple_vIEw))        .check(matches(withText("111")));  }  @Test  public voID buttontest() throws Exception {    onVIEw(withID(R.ID.btn_simple_vIEw))        .check(matches(withText("222")))        .perform(click());    onVIEw(withID(R.ID.tv_simple_vIEw))        .check(matches(withText("777")));  }}

测试主要逻辑:

1、首先要使用ActivityTestRule初始化你要测试的Activity。

2、编写测试方法,测试VIEw是否是我们预期的样子。

两个测试方法逻辑如下:

textVIEwtest():

在Activity中查找ID为tv_simple_vIEw的VIEw,检查它的text是否为“111”。

buttontest():

在Activity中查找ID为btn_simple_vIEw的VIEw,检查它的text是否为“222”。然后执行点击事件,点击事件的逻辑是在Activity的OnCreate中设置的,是把TextVIEw的text设置为777。在执行完点击事件后,测试方法中继续测试TextVIEw的text是否为“777”。

读者可能阅读到对VIEw的测试非常陌生,不用担心,此处主要要理解测试的逻辑即可,笔者会在下篇文章具体讲解VIEw的各种测试方法。

网络获取String的Activity测试:

package com.example.xujiajia_sx.myexpressotest;import androID.app.Activity;import androID.os.Bundle;import androID.support.annotation.Nullable;import androID.Widget.TextVIEw;/** * Created by xujiajia_sx on 2017/8/14. */public class ActTestActivity extends Activity{  private TextVIEw tv;  @OverrIDe  protected voID onCreate(@Nullable Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentVIEw(R.layout.act_act_test);    initVIEw();  }  private voID initVIEw() {    tv= findVIEwByID(R.ID.tv_act_test);    new Thread(new Runnable() {      @OverrIDe      public voID run() {        String url =getIntent().getStringExtra("url");        final String s=mhttpClIEnt.getInstance().get(url);        runOnUiThread(new Runnable() {          @OverrIDe          public voID run() {            tv.setText(s);          }        });      }    }).start();  }}
package com.example.xujiajia_sx.myexpressotest;/** * Created by xujiajia_sx on 2017/8/14. */public class mhttpClIEnt {  private static httpURLConnectionClIEnt mClIEnt = null;  public static voID setClIEnt(httpURLConnectionClIEnt clIEnt) {    mClIEnt = clIEnt;  }  public static httpURLConnectionClIEnt getInstance() {    return mClIEnt;  }}
package com.example.xujiajia_sx.myexpressotest;import androID.util.Log;import java.io.BufferedReader;import java.io.IOException;import java.io.inputStream;import java.io.inputStreamReader;import java.net.httpURLConnection;import java.net.URL;import static androID.content.ContentValues.TAG;/** * Created by xujiajia_sx on 2017/8/14. */public class httpURLConnectionClIEnt {  public String get(String url) {    httpURLConnection conn = null;    try {      URL mURL = new URL(url);      conn = (httpURLConnection) mURL.openConnection();      conn.setRequestMethod("GET");      conn.setConnectTimeout(2000);      conn.connect();      inputStream is = conn.getinputStream();      StringBuilder sb = new StringBuilder();      BufferedReader reader = new BufferedReader(new inputStreamReader(is));      String line;      while ((line = reader.readline()) != null) {        sb.append(line).append("\n");      }      reader.close();      return sb.toString();    } catch (IOException e) {      Log.e(TAG,"network error for mini program ",e);      return "";    } finally {      //最后将conn断开连接      if (conn != null) {        conn.disconnect();      }    }  }}
<?xml version="1.0" enCoding="utf-8"?><linearLayout xmlns:androID="http://schemas.androID.com/apk/res/androID"  androID:layout_wIDth="match_parent"  androID:layout_height="match_parent"  androID:orIEntation="vertical">  <TextVIEw    androID:ID="@+ID/tv_act_test"    androID:layout_wIDth="wrap_content"    androID:layout_height="wrap_content"    /></linearLayout>
package com.example.xujiajia_sx.myexpressotest;import androID.content.Intent;import androID.support.test.rule.ActivityTestRule;import org.junit.Rule;import org.junit.Test;/** * Created by xujiajia_sx on 2017/8/14. */public class ActTest {  @Rule  public ActivityTestRule<ActTestActivity> mActivityTestRule=      new ActivityTestRule<ActTestActivity>(ActTestActivity.class){        @OverrIDe        protected Intent getActivityIntent() {          Intent intent=new Intent();          intent.putExtra("url","http://www.weather.com.cn/adat/sk/101310201.HTML");          return intent;        }        @OverrIDe        protected voID beforeActivityLaunched() {          mhttpClIEnt.setClIEnt(new httpURLConnectionClIEnt());        }      };  @Test  public voID mtest() throws Exception{    Thread.sleep(5000);  }}

网络获取不要忘记在AndroIDManifest中加网络权限喔。

这个Activity的主要逻辑就是接收Intent,然后获取到传过来的url,接着通过网络获取到url的String,显示到TextVIEw上。

主要测试逻辑:

首先还是要定义ActivityTestRule,确定使用哪个Activity。

与前一个例子不同的是,这里要重写ActivityTestRule的两个方法,getActivityIntent() 和beforeActivityLaunched()。顾名思义,一个是设置Activity获取到的Intent,另一个是设置Activity启动跟之前的准备工作。

笔者此处在getActivityIntent() 中设置了传递的url,在beforeActivityLaunched()设置的网络获取的方式。

有些读者可能会好奇为什么网络获取的方式不默认呢,而要通过setClIEnt()来设置?

因为这样可以更方便我们测试,在正式的项目中,我们可能会需要在代码中加入log等 *** 作,但是正式的代码一般我们是不会去修改的,但是我们可以继承它,重写某些方法,然后把它放到测试需要的地方。

在这里我们就可以继承httpURLConnectionClIEnt 这个类,然后把继承的子类使用setClIEnt()来作为网络获取的方式。

总结

Activity的使用方法大致如此了,如果有更多需求的读者可以查看一下官方ActivityTestRule的Reference。

链接如下:https://developer.android.google.cn/reference/android/support/test/rule/ActivityTestRule.html

第一种使用方法中设计到了对VIEw的测试,由于篇幅较大,本篇文章未能详细讲述,笔者会在下篇文章做一定讲解。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。

总结

以上是内存溢出为你收集整理的Android单元测试之对Activity的测试示例全部内容,希望文章能够帮你解决Android单元测试之对Activity的测试示例所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/web/1144775.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-31
下一篇2022-05-31

发表评论

登录后才能评论

评论列表(0条)

    保存