如何对android模块进行单元测试



我有一个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构建系统在Gradle构建文件中使用以下配置为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);
}
}

通过运行测试测试,确保单元测试得到正确实现。它们应该成功运行。请参阅此链接