Android 单元测试

2016-10-14  本文已影响0人  yoosir

一、浏览 Android 单元测试 官网

Android 的单元测试有两种方式:JUnit test(本地虚拟机测试) 和 instrumented test(设备测试)。

a JUnit test that runs on the local JVM or an instrumented test that runs on a device

Local unit testsLocated at module-name/src/test/java/ 可以本地虚拟机测试,只能调用Java API ,不能调用 Android API 。不过,可以通过依赖 android.jar 或者 第三方库(如:Mockito)调用 Android API。
Instrumented testsLocated at module-name/src/androidTest/java/ 在设备上运行,可以调试Android API,并可自定义测试配置文件。通过依赖第三方库(如:Espresso)可以实现 UI testing.

二、环境配置

the test library dependencies in your app module's build.gradle file:

dependencies {  
    // Required for local unit tests (JUnit 4 framework) 
    testCompile 'junit:junit:4.12' 
     // Required for instrumented tests  
    androidTestCompile 'com.android.support:support-annotations:24.0.0' 
    androidTestCompile 'com.android.support.test:runner:0.5'
}

单元测试在项目中的目录结构:


Paste_Image.png

配置问题:

  1. Conflict with dependency 'com.android.support:support-annotations'. Resolved versions for app (23.3.0) and test app (23.1.1) differ
    解决方案 :参考官网

To use JUnit 4 test classes, make sure to specify AndroidJUnitRunner as the default test instrumentation runner in your project by including the following setting in your app's module-level build.gradle file:

android { 
   defaultConfig { 
       testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 
   }
}

上面是配置,然后添加下面这句:

 android{
    configurations.all {  
        resolutionStrategy.force 'com.android.support:support-annotations:23.1.0'
    }
}

三、创建 Test 文件

Create a Local Unit Test Class
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)); 
   }  
  ...}
Create an Instrumented Unit Test Class
import org.junit.Before;import org.junit.Test;
import org.junit.runner.RunWith;
/**
 *   RxJava simple test
 * Created by ys on 2016/10/14 0014.
 */
@RunWith(AndroidJUnit4.class)
@SmallTest
public class RxJavaSimpleTest { 

   private RxJavaSimple mRxJavaSimple; 
   @Before 
   public void createRxJavaSimple(){ 
       mRxJavaSimple = new RxJavaSimple(); 
   }  
  @Test  
  public void testScheduler(){ 
        //打印 Log
       mRxJavaSimple.testScheduler(); 
   }
}

四、Run Test

To run your instrumented 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:

三种方式:

  1. 运行单个 Test,右键 -> Run。
  2. 运行单个Test 文件,右键 class -> Run。
  3. 运行文件夹中所有Test,右键文件夹-> Run tests。
上一篇 下一篇

猜你喜欢

热点阅读