Android學習6—單元測試的使用

來源:互聯網
上載者:User

標籤:android   style   blog   http   java   使用   檔案   io   

在這裡對單元測試的使用,主要介紹兩種方法,1、手動添加配置資訊,然後編寫測試類別。2、通過Eclipse建立測試專案

1、手動添加配置資訊,然後編寫測試類別:

待測試的類:/src/com/example/unittest/UnitTestDemo1.java

package com.example.unittest;
//此類為待測試類別
public class UnitTestDemo1 {
    public void testing1(String str){
        String tempStr = str.trim();
    }
   
    public int testing2(int num1, int num2){
        return num1 + num2;
    }
}

在資訊清單檔AndroidManifest.xml中進行配置:

使用紅色方框標出來的內容為需要添加的配置資訊,其中<instrumentation>中的target屬性工作表示的是待測試的類所在的包,label屬性任意

 

添加好配置資訊之後,進行測試類別的編寫,測試類別需要繼承AndroidTestCase

package com.example.unittest1;

import junit.framework.Assert;

import com.example.unittest.UnitTestDemo1;

import android.test.AndroidTestCase;

public class UnitTest extends AndroidTestCase{
    public void testTesting1() throws Exception{
        UnitTestDemo1 ut1 = new UnitTestDemo1();
        ut1.testing1(" zhanghao ");
    }
   
    public void testTesting2() throws Exception{
        UnitTestDemo1 ut1 = new UnitTestDemo1();
        int tempResult = ut1.testing2(1, 1);
        Assert.assertEquals(2, tempResult);
    }
}

注意,測試類別中的方法使用public void修飾,不可改變。

在測試類別編寫好之後,在該類的outlook視圖中,選擇相應的方法右鍵—>Run As—>Android Junit Test運行即可

如果測試通過,則在JUnit視圖中顯示:

若測試失敗,則顯示為:

 

2.通過Eclipse建立測試工程

在Eclipse中建立一個Android Test Project

新建立一個工程之後,點擊下一步,填寫項目名稱,之後在選擇一個已有的工程,然後點擊完成

 

 

這樣之後即可在新建立的工程中編寫測試代碼,用來測試待測試的項目中的內容了。O(∩_∩)O~

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.