android studio 单元测试

在Android Studio进行“简单配置”单元测试(Android Junit)


  1. 本文基于做过Eclipse开发使用过Android junit,如果Eclipse的Android Junit没有使用过,就我没有说过吧!
  2. 准备环境,配置
    1. 官网Demo地址:https://github.com/googlesamples/android-testing-templates.git
    2. 环境
      1. 根据demo中
        1. 单纯想运行java的单元测试就引入
          // Dependencies for local unit tests
          testCompile 'junit:junit:' + rootProject.ext.junitVersion
          testCompile 'org.mockito:mockito-all:' + rootProject.ext.mockitoVersion
          testCompile 'org.hamcrest:hamcrest-all:' + rootProject.ext.hamcrestVersion
        2. 想运行Android的Junit得引入
          // Android Testing Support Library's runner and rules
          androidTestCompile 'com.android.support.test:runner:' + rootProject.ext.runnerVersion
          androidTestCompile 'com.android.support.test:rules:' + rootProject.ext.rulesVersion
      2. 最后在   defaultConfig 节点添加


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


      3. 以上配置要配置在“启动项目中”build.gradle文件中,方可自动关联上启动项目

        1. Android Studio本来启动项目中的测试代码分为两个目录
        2. 如果是通过更改“sourceSets”的话。那就要得重新配置注明相应的文件夹(这是Eclipse转AS导出的配置)
          sourceSets{
          sourceSets{
          main{
          java.srcDirs = ['src']
          }
          androidTest{
          java.srcDirs = ['androidTest/src']
          }
          test{
          java.srcDirs = ['test/src']
          }
          }
        3. 最后就把相应的文件放入具体目录
          1. androidTest  “Android的Junit”
          2. test “java的单元测试”
  3. 代码
    1. junit
      public class ExampleUnitTest {
      @Test
      public void addition_isCorrect() throws Exception {
      System.out.println("123");

      }
      }
    2. Android junit
      public class AndroidRuntimeCodeTest extends AndroidTestCase {

      public void testHello() throws Exception {
      System.out.println("testHello");
      }
      }
  4. 结论
    1. 注意事项
      1. 以前Eclipse做单元测试得往AndroidManifest.xml标明

        1. <manifest >
          <instrumentation
                  android:name="android.test.InstrumentationTestRunner"
                  android:targetPackage="com.example.viewtest" />
          </manifest>
        2. <application>
          <uses-library android:name="android.test.runner" />
          </application>
      2. Android studio就要在build.gradle
        1. 导入相应的包

        2. android{
              defaultConfig {
                  testInstrumentationRunner 'android.support.test.runner.AndroidJUnitRunner'
              }
          }
    2. 还有一点:就是“测试使用的需要的包”遇到与“启动项目的包”冲突时,使用
      configurations.all {
      resolutionStrategy {
      androidTestCompile 'com.android.support.test:runner:0.4.1'
      androidTestCompile 'com.android.support.test:rules:0.4.1'

      forcedModules = ['com.android.support:support-annotations:23.0.1']

      }
      }
posted @ 2016-07-25 14:40  阿金好掂  阅读(191)  评论(0编辑  收藏  举报