Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

在 Android Studio 中進行單元測試與 UI 測試

編輯:關於 Android 程式設計

「不會寫單元測試的 Android 工程師不是合格的工程師。」

學 Android 也有一段時間了,最近換到 Android Studio,才發現它自帶單元測試支援,於是花時間把用法梳理了一遍,記錄在此。

一個前置提醒:測試代碼中盡量不要依賴全局變量,因為單元測試拿不到全局變量的值。另外除了 IDE 自帶能力,市面上還有不少測試框架值得後續深入。

被測對象:一個簡單計算器

先準備一個待測的 Activity。核心邏輯集中在兩個方法:compute 負責解析並計算表達式,clickOp / clickNumber 負責按鈕行為。

public class MainActivity extends AppCompatActivity {

    EditText ContentText;
    Button CButton, DivButton, MulButton, DelButton;
    Button SevenButton, EightButton, NineButton, SubButton;
    Button FourButton, FiveButton, SixButton, AdditionButton;
    Button OneButton, TwoButton, ThreeButton, RemainderButton;
    Button ZeroButton, EqualButton;

    boolean isClickEqu = false;   // 是否點擊過等號

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ContentText = (EditText) findViewById(R.id.content_text);
        CButton = (Button) findViewById(R.id.c_button);
        // ……其餘按鈕的 findViewById 省略

        // 統一註冊同一個監聽器
        CButton.setOnClickListener(new MyClickListener());
        DivButton.setOnClickListener(new MyClickListener());
        MulButton.setOnClickListener(new MyClickListener());
        // ……
    }

    /**
     * 解析並計算表達式
     */
    public double compute(String text) {
        double result = 0;
        double num1 = 0;
        double num2 = 0;
        char temp = 0;

        if (text.contains("+")) {
            temp = '+';
        } else if (text.contains("-")) {
            temp = '-';
        } else if (text.contains("*")) {
            temp = '*';
        } else if (text.contains("/")) {
            temp = '/';
        } else if (text.contains("%")) {
            temp = '%';
        }

        try {
            num1 = Double.valueOf(text.substring(0, text.lastIndexOf(temp)));
            num2 = Double.valueOf(text.substring(text.lastIndexOf(temp) + 1));
        } catch (Exception e) {
            num1 = 0;
            num2 = 0;
        }

        if (temp == '+') {
            result = num1 + num2;
        } else if (temp == '-') {
            result = num1 - num2;
        } else if (temp == '*') {
            result = num1 * num2;
        } else if (temp == '/') {
            result = num1 / num2;
        } else if (temp == '%') {
            result = num1 % num2;
        }
        return result;
    }

    public void clickNumber(int n) {
        if (isClickEqu) {
            ContentText.setText(String.valueOf(n));
            isClickEqu = false;
        } else {
            String text = ContentText.getText().toString();
            ContentText.setText(text + String.valueOf(n));
        }
    }

    public void clickOp(char temp) {
        String text = ContentText.getText().toString();
        if (temp == '+' || temp == '-' || temp == '*' || temp == '/' || temp == '%') {
            if (text == null || text.equals("")
                    || text.contains("+") || text.contains("-")
                    || text.contains("*") || text.contains("/") || text.contains("%")) {
                return;
            }
            isClickEqu = false;
            ContentText.setText(text + temp);
        } else if (temp == '=') {
            if (text == null || text.equals("")) {
                return;
            }
            double result = compute(text);
            ContentText.setText(String.valueOf(result));
            isClickEqu = true;
        } else if (temp == 'd') {          // 退格
            isClickEqu = false;
            try {
                ContentText.setText(text.substring(0, text.length() - 1));
            } catch (Exception e) {
                ContentText.setText("");
            }
        } else if (temp == 'c') {          // 清空
            isClickEqu = false;
            ContentText.setText("");
        }
    }

    class MyClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.c_button:       clickOp('c'); break;
                case R.id.del_button:     clickOp('d'); break;
                case R.id.addition_button: clickOp('+'); break;
                case R.id.sub_button:     clickOp('-'); break;
                case R.id.mul_button:     clickOp('*'); break;
                case R.id.div_button:     clickOp('/'); break;
                case R.id.remainder_button: clickOp('%'); break;
                case R.id.equal_button:   clickOp('='); break;
                case R.id.zero_button:    clickNumber(0); break;
                case R.id.one_button:     clickNumber(1); break;
                // ……其餘數字鍵同理
            }
        }
    }
}

編寫測試類

測試類繼承 ActivityInstrumentationTestCase2,這樣既能拿到被測 Activity 與其上的控件(適合做 UI 層驗證),也能直接調用 public 方法做純邏輯驗證。

public class MainActivityTest extends ActivityInstrumentationTestCase2<MainActivity> {

    private MainActivity mActivity;
    Instrumentation mInstrumentation;
    EditText ContentText;
    Button CButton, DivButton, MulButton, DelButton;
    Button SevenButton, EightButton, NineButton, SubButton;
    Button FourButton, FiveButton, SixButton, AdditionButton;
    Button OneButton, TwoButton, ThreeButton, RemainderButton;
    Button ZeroButton, EqualButton;

    public MainActivityTest() {
        super(MainActivity.class);
    }

    @Override
    public void setUp() throws Exception {
        super.setUp();
        setActivityInitialTouchMode(false);
        mInstrumentation = getInstrumentation();
        mActivity = getActivity();          // 啟動被測 Activity

        ContentText = (EditText) mActivity.findViewById(R.id.content_text);
        CButton = (Button) mActivity.findViewById(R.id.c_button);
        // ……其餘控件初始化省略
    }

    @Test
    public void testPreCondition() {
        // 前提驗證:所有控件都必須成功綁定
        assertNotNull(mActivity);
        assertNotNull(ContentText);
        assertNotNull(CButton);
        assertNotNull(DivButton);
        assertNotNull(MulButton);
        // ……
    }

    @Test
    public void testcompute() throws Exception {
        assertEquals(0d, mActivity.compute("0"));
        assertEquals(0d, mActivity.compute("1234"));
        assertEquals(3d, mActivity.compute("1+2"));
        assertEquals(55d, mActivity.compute("11+44"));
        assertEquals(11111111155d, mActivity.compute("11111111111+44"));
        assertEquals(1d, mActivity.compute("2-1"));
        assertEquals(-1d, mActivity.compute("1-2"));
        assertEquals(2d, mActivity.compute("1*2"));
        assertEquals(2d, mActivity.compute("2/1"));
        assertEquals(1.5d, mActivity.compute("3/2"));
        // 邊界情況:除以零與取模零
        assertEquals(Double.POSITIVE_INFINITY, mActivity.compute("2/0"));
        assertEquals(Double.NaN, mActivity.compute("5%0"));
        assertEquals(1d, mActivity.compute("3%2"));
        assertEquals(0d, mActivity.compute("3%1"));
    }

    @Test
    public void testclickNumber() throws Exception {
        // 可透過 mInstrumentation 模擬點擊後再斷言 UI 狀態
    }

    @Test
    public void testclickOp() throws Exception {
        // 同上
    }
}

testcompute 是這套測試裡最有價值的部分:它用一組輸入輸出對,把加減乘除、取模、邊界值(除零、取模零)全部覆蓋到了。這正是單元測試的意義——把「我以為它對」變成「我驗證過它對」。

幾點實踐建議

· 先寫可測的代碼,再寫測試。像 compute 這樣把計算邏輯從回調中剝離出來,獨立成一個接收字串、返回結果的方法,是能被測試的前提。邏輯若全塞在 onClick 裡,測試會非常痛苦。
· 基類盡量不要依賴。ActivityInstrumentationTestCase2 需要模擬器或真機,速度較慢。純邏輯應該抽剝到普通 Java 類中,用 JUnit 在 JVM 上跑,毫秒級完成。
· 注意 ActivityInstrumentationTestCase2 已廢棄。新項目應改用 ActivityTestRule + AndroidJUnitRunner,UI 測試則使用 Espresso。
· 計算器的求值邏輯本身有缺陷:它只支持兩個運算數、不支持運算優先級,且用 lastIndexOf 定位運算符會在多運算符場景下出錯。這類問題恰恰只有寫了測試才會暴露,也是測試的價值所在。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved