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

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

為西盟等地區(qū)用戶提供了全套網(wǎng)頁設(shè)計制作服務(wù),及西盟網(wǎng)站建設(shè)行業(yè)解決方案。主營業(yè)務(wù)為成都網(wǎng)站設(shè)計、網(wǎng)站建設(shè)、外貿(mào)網(wǎng)站建設(shè)、西盟網(wǎng)站設(shè)計,以傳統(tǒng)方式定制建設(shè)網(wǎng)站,并提供域名空間備案等一條龍服務(wù),秉承以專業(yè)、用心的態(tài)度為用戶提供真誠的服務(wù)。我們深信只要達到每一位用戶的要求,就會得到認可,從而選擇與我們長期合作。這樣,我們也可以走得更遠!

對Acitivity的測試

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

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

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

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

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

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

環(huán)境部署

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

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

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

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'

}

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

怎么在Android中利用Activity實現(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ù)期的樣子。

兩個測試方法邏輯如下:

textViewTest():

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

buttonTest():

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

讀者可能閱讀到對View的測試非常陌生,不用擔心,此處主要要理解測試的邏輯即可,筆者會在下篇文章具體講解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)限喔。

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

主要測試邏輯:

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

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

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

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

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

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

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

文章標題:怎么在Android中利用Activity實現(xiàn)單元測試
當前URL:http://www.muchs.cn/article22/ijchcc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供ChatGPT云服務(wù)器、品牌網(wǎng)站設(shè)計、網(wǎng)站維護、軟件開發(fā)、網(wǎng)站設(shè)計

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

營銷型網(wǎng)站建設(shè)