Building Local Unit Tests

来源:http://www.cnblogs.com/taoyexian/archive/2016/07/18/5681943.html
-Advertisement-
Play Games

If your unit test has no dependencies or only has simple dependencies on Android, you should run your test on a local development machine. This testin ...


If your unit test has no dependencies or only has simple dependencies on Android, you should run your test on a local development machine. This testing approach is efficient because it helps you avoid the overhead of loading the target app and unit test code onto a physical device or emulator every time your test is run. Consequently, the execution time for running your unit test is greatly reduced. With this approach, you normally use a mocking framework, like Mockito, to fulfill any dependency relationships.

Set Up Your Testing Environment


In your Android Studio project, you must store the source files for local unit tests at module-name/src/test/java/. This directory already exists when you create a new project.

You also need to configure the testing dependencies for your project to use the standard APIs provided by the JUnit 4 framework. If your test needs to interact with Android dependencies, include theMockito library to simplify your local unit tests. To learn more about using mock objects in your local unit tests, see Mocking Android dependencies.

In your app's top-level build.gradle file, you need to specify these libraries as dependencies:

dependencies {
    // Required -- JUnit 4 framework
    testCompile 'junit:junit:4.12'
    // Optional -- Mockito framework
    testCompile 'org.mockito:mockito-core:1.10.19'
}

Create a Local Unit Test Class


Your local unit test class should be written as a JUnit 4 test class. JUnit is the most popular and widely-used unit testing framework for Java. The latest version of this framework, JUnit 4, allows you to write tests in a cleaner and more flexible way than its predecessor versions. Unlike the previous approach to Android unit testing based on JUnit 3, with JUnit 4, you do not need to extend the junit.framework.TestCase class. You also do not need to prefix your test method name with the ‘test’ keyword, or use any classes in the junit.framework or junit.extensions package. 

//JUnit是最流行的和廣泛使用的Java測試框架。最近的版本Junit4比之前的版本都更加簡潔和流暢。你也不需要繼承TestCase類,你也不需要強制讓測試方法的首碼為test

To create a basic JUnit 4 test class, create a Java class that contains one or more test methods. A test method begins with the @Test annotation and contains the code to exercise and verify a single functionality in the component that you want to test.

The following example shows how you might implement a local unit test class. The test method emailValidator_CorrectEmailSimple_ReturnsTrueverifies that the isValidEmail() method in the app under test returns the correct result.

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("[email protected]"), is(true));
    }
    ...
}

To test that components in your app return the expected results, use the junit.Assert methods to perform validation checks (or assertions) to compare the state of the component under test against some expected value. To make tests more readable, you can use Hamcrest matchers (such as the is() and equalTo() methods) to match the returned result against the expected result.

Mock Android dependencies

By default, the Android Plug-in for Gradle executes your local unit tests against a modified version of the android.jar library, which does not contain any actual code. Instead, method calls to Android classes from your unit test throw an exception.

You can use a mocking framework to stub out external dependencies in your code, to easily test that your component interacts with a dependency in an expected way. By substituting Android dependencies with mock objects, you can isolate your unit test from the rest of the Android system while verifying that the correct methods in those dependencies are called. The Mockito mocking framework for Java (version 1.9.5 and higher) offers compatibility with Android unit testing. With Mockito, you can configure mock objects to return some specific value when invoked.

To add a mock object to your local unit test using this framework, follow this programming model:

  1. Include the Mockito library dependency in your build.gradle file, as described in Set Up Your Testing Environment.
  2. At the beginning of your unit test class definition, add the @RunWith(MockitoJUnitRunner.class) annotation. This annotation tells the Mockito test runner to validate that your usage of the framework is correct and simplifies the initialization of your mock objects.
  3. To create a mock object for an Android dependency, add the @Mock annotation before the field declaration.
  4. To stub the behavior of the dependency, you can specify a condition and return value when the condition is met by using the when() andthenReturn() methods.

The following example shows how you might create a unit test that uses a mock Context object.

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() {
        // Given a mocked Context injected into the object under test...
        when(mMockContext.getString(R.string.hello_word))
                .thenReturn(FAKE_STRING);
        ClassUnderTest myObjectUnderTest = new ClassUnderTest(mMockContext);

        // ...when the string is returned from the object under test...
        String result = myObjectUnderTest.getHelloWorldString();

        // ...then the result should be the expected one.
        assertThat(result, is(FAKE_STRING));
    }
}

To learn more about using the Mockito framework, see the Mockito API reference and the SharedPreferencesHelperTest class in the sample code.

Run Local Unit Tests


To run your local unit tests, follow these steps:

  1. Be sure your project is synchronized with Gradle by clicking Sync Project  in the toolbar.
  2. Run your test in one of the following ways:
    • To run a single test, open the Project window, and then right-click a test and click Run .
    • To test all methods in a class, right-click a class or method in the test file and click Run .
    • To run all tests in a directory, right-click on the directory and select Run tests .

The Android Plugin for Gradle compiles the local unit test code located in the default directory (src/test/java/), builds a test app, and executes it locally using the default test runner class. Android Studio then displays the results in the Run window.


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 表單校驗是頁面開發中非常常見的一類需求,相信每個前端開發人員都有這方面的經驗。網上有很多成熟的表單校驗框架,雖然按照它們預設的設計,用起來沒有多大的問題,但是在實際工作中,表單校驗有可能有比較複雜的個性化的需求,使得我們用這些插件的預設機制並不能完成這些功能,所以要根據自己的需要去改造它們(畢竟自己 ...
  • [1]創建 [2]本質 [3]稀疏 [4]長度 [5]遍歷 [6]類數組 ...
  • 本章內容: 定義 節點類型 節點關係 選擇器 樣式操作方法style 表格操作方法 表單操作方法 元素節點ELEMENT 屬性節點attributes 文本節點TEXT 文檔節點 Document 位置操作方法 定時器 彈出框 location 其它 事件操作 實例 定義 文檔對象模型(Docume ...
  • (幾個重點概念解析) 一、層疊上下文 二、層疊水平 三、層疊順序(以下層疊順序按照由內向外排列,即z軸上的值越來越大,越靠近用戶) 四、z-index 五、我的理解: 頁面中元素的層疊情況是由層疊順序這個規則決定的。在最初的頁面里,所有元素按照預設的情況依次排列。而z-index屬性像是一個外來戶, ...
  • $('div a'):div標簽下所有層次a元素的jquery對象 $('div>a'):div標簽下子元素層次a元素的jquery對象 ...
  • PlaceholderTextView 效果 源碼 https://github.com/YouXianMing/UI-Component-Collection 的 PlaceholderTextView ...
  • 剛剛請教了一個php高手。就hao123.com 來舉例。因為要考慮到一個公司的多個app。所以 如下樣式,如果公司名稱簡稱xtz,app的 名稱簡稱cht xtz.hao123.com xtzcht.hao123.com 如果是測試的話:test_xtzcht.hao123.com baiduap ...
  • Mac下載並編譯Google安卓AOSP項目代碼 參考 這兩天用Mac下載安卓AOSP源碼,且把遇到的問題記下來。當然作為一個菜鳥,難免會有錯誤或者描述不對的地方,歡迎各路大神小神批評指正。轉載請註明出處。 一、準備環境 (請提前安裝好xcode或command line tools) Instal ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...