[英]how to unit test an android module
我有一個 android 庫模塊,我想向其中添加單元測試。 我是否需要在項目中擁有模塊才能運行測試? 有沒有辦法獨立於項目測試模塊?
要為您的 Android 應用程序使用 JUnit 測試,您需要將其作為依賴項添加到您的 Gradle 構建文件中。
dependencies {
// Unit testing dependencies
testCompile 'junit:junit:4.12'
// Set this dependency if you want to use the Hamcrest matcher library
testCompile 'org.hamcrest:hamcrest-library:1.3'
// more stuff, e.g., Mockito
}
您還可以指示 Gradle 構建系統返回 android.jar 中方法調用的默認值,並在您的android.jar
文件中使用以下配置。
android {
// ...
testOptions {
unitTests.returnDefaultValues = true
}
}
In your app/src/test directory create the following two test methods for the ConverterUtil class.
package com.vogella.android.temperature.test;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.vogella.android.temperature.ConverterUtil;
public class ConverterUtilTest {
@Test
public void testConvertFahrenheitToCelsius() {
float actual = ConverterUtil.convertCelsiusToFahrenheit(100);
// expected value is 212
float expected = 212;
// use this method because float is not precise
assertEquals("Conversion from celsius to fahrenheit failed", expected, actual,
0.001);
}
@Test
public void testConvertCelsiusToFahrenheit() {
float actual = ConverterUtil.convertFahrenheitToCelsius(212);
// expected value is 100
float expected = 100;
// use this method because float is not precise
assertEquals("Conversion from celsius to fahrenheit failed", expected, actual,
0.001);
}
}
通過運行測試測試確保您的單元測試正確實施。 他們應該成功運行。 參考這個鏈接
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.