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

我有一个想要向其添加单元测试的android库模块。 我是否需要在项目中安装模块才能运行测试? 有没有办法独立于项目测试模块?

bozipk 回答:如何对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中使用以下配置在Gradle构建文件中返回方法调用的默认值。

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",0.001);
 }

 }

通过运行测试来确保正确执行了单元测试。它们应该运行成功。refer this link

本文链接:https://www.f2er.com/3120074.html

大家都在问