二、Android構建本地單元測試

若是你的單元測試在Android中沒有依賴或者只有簡單的以來,你能夠在你的本地開發環境中運行你的測試。這種測試比較高效由於它能讓你避免將整個app安裝到物理設備或虛擬機中執行單元測試。最後,執行單元測試的時間大量減小。你能夠經過模擬框架,好比Mockito來模擬依賴關係。java

配置你的測試環境

前文已經敘述。android

建立一個本地單元類

你的本地測試單元類風格相似Junit 4測試類。Junit是Java最流行應用最普遍的單元測試類。最新的版本,Junit 4,容許你用比以前版本更簡潔和靈活的方式編寫測試。跟以前的版本不一樣,在Junit 4中,你不須要擴展junit.framework.TestCase類了。你也不須要在每一個測試方法前加前綴test或者使用在junit.framework 或 junit.extensions中的包。
建立一個基本的Junit 4 測試類,你能夠建立一個包含一個或多個測試方法的Java類。每一個測試方法都用@Test 標註。以下:markdown

import org.junit.Test;
import java.util.regex.Pattern;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

public class EmailValidatorTest {

    @Test
    public void emailValidator_CorrectEmailSimple_ReturnsTrue() {
        assertThat(EmailValidator.isValidEmail("name@email.com"), is(true));
    }
}

爲了測試你的APP組件返回指望的記過,使用Assert方法來執行檢查。app

模擬Android 依賴

默認狀況下,Gradle的安卓插件依靠一個通過修改的android.jar的庫,不包含任何真正的代碼,調用的任何的Android的類都被視爲異常。
你可使用一個模擬框架來排除你代碼中額外的依賴,讓你的組件經過指望的方式與依賴交互。
添加一個虛擬對象到你的本地單元測試,跟隨以下幾步:
一、 將Mockito依賴添加到build.gradle文件中
二、 在你的測試類前添加@RunWith(MockitoJUnitRunner.class)註解。
三、 建立一個mock對象,用@Mock註解框架

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.CoreMatchers.*;
import static org.mockito.Mockito.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import android.content.SharedPreferences;

@RunWith(MockitoJUnitRunner.class)
public class UnitTestSample {

    private static final String FAKE_STRING = "HELLO WORLD";

    @Mock
    Context mMockContext;

    @Test
    public void readStringFromContext_LocalizedString() {
        when(mMockContext.getString(R.string.hello_word))
                .thenReturn(FAKE_STRING);
        ClassUnderTest myObjectUnderTest = new ClassUnderTest(mMockContext);
        String result = myObjectUnderTest.getHelloWorldString();
        assertThat(result, is(FAKE_STRING));
    }
}

本文做者:宋志輝
我的微博:點擊進入單元測試

相關文章
相關標籤/搜索