溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么在Android中利用Activity實(shí)現(xiàn)單元測試

發(fā)布時(shí)間:2021-04-08 16:21:47 來源:億速云 閱讀:220 作者:Leah 欄目:移動開發(fā)

這期內(nèi)容當(dāng)中小編將會給大家?guī)碛嘘P(guān)怎么在Android中利用Activity實(shí)現(xiàn)單元測試,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。

對Acitivity的測試

對于Activity,我們大致有兩種測試需求:

1、在Activity正常啟動后,查看界面布局是否正確,包括View的點(diǎn)擊事件等是否正確。

2、需要在Activity啟動前完成各種數(shù)據(jù)的部署,然后查看Activity的效果。

對于這兩種需求,筆者分別做了兩個(gè)示例解說:

1、檢測一個(gè)布局中的button和TextView是否正確。

2、從網(wǎng)絡(luò)動態(tài)獲取String到Activity界面顯示,并且這個(gè)圖片的URL是由Intent傳遞過來的。

環(huán)境部署

首先要導(dǎo)入expresso-core的包,如下:

dependencies {
  // Other dependencies ...
  androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'
}

當(dāng)然在目前的項(xiàng)目架構(gòu)中一般已經(jīng)自動導(dǎo)入了這個(gè)包,所以不需要自己導(dǎo)入,筆者項(xiàng)目中自動導(dǎo)入的包如下如下:

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'

}

項(xiàng)目結(jié)構(gòu)如下:

怎么在Android中利用Activity實(shí)現(xiàn)單元測試

布局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是否是我們預(yù)期的樣子。

兩個(gè)測試方法邏輯如下:

textViewTest():

在Activity中查找id為tv_simple_view的View,檢查它的text是否為“111”。

buttonTest():

在Activity中查找id為btn_simple_view的View,檢查它的text是否為“222”。然后執(zhí)行點(diǎn)擊事件,點(diǎn)擊事件的邏輯是在Activity的OnCreate中設(shè)置的,是把TextView的text設(shè)置為777。在執(zhí)行完點(diǎn)擊事件后,測試方法中繼續(xù)測試TextView的text是否為“777”。

讀者可能閱讀到對View的測試非常陌生,不用擔(dān)心,此處主要要理解測試的邏輯即可,筆者會在下篇文章具體講解View的各種測試方法。

網(wǎng)絡(luò)獲取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);
  }


}

網(wǎng)絡(luò)獲取不要忘記在AndroidManifest中加網(wǎng)絡(luò)權(quán)限喔。

這個(gè)Activity的主要邏輯就是接收Intent,然后獲取到傳過來的url,接著通過網(wǎng)絡(luò)獲取到url的String,顯示到TextView上。

主要測試邏輯:

首先還是要定義ActivityTestRule,確定使用哪個(gè)Activity。

與前一個(gè)例子不同的是,這里要重寫ActivityTestRule的兩個(gè)方法,getActivityIntent() 和beforeActivityLaunched()。顧名思義,一個(gè)是設(shè)置Activity獲取到的Intent,另一個(gè)是設(shè)置Activity啟動跟之前的準(zhǔn)備工作。

筆者此處在getActivityIntent() 中設(shè)置了傳遞的url,在beforeActivityLaunched()設(shè)置的網(wǎng)絡(luò)獲取的方式。

有些讀者可能會好奇為什么網(wǎng)絡(luò)獲取的方式不默認(rèn)呢,而要通過setClient()來設(shè)置?

因?yàn)檫@樣可以更方便我們測試,在正式的項(xiàng)目中,我們可能會需要在代碼中加入log等操作,但是正式的代碼一般我們是不會去修改的,但是我們可以繼承它,重寫某些方法,然后把它放到測試需要的地方。

在這里我們就可以繼承HttpURLConnectionClient 這個(gè)類,然后把繼承的子類使用setClient()來作為網(wǎng)絡(luò)獲取的方式。


上述就是小編為大家分享的怎么在Android中利用Activity實(shí)現(xiàn)單元測試了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI