简体   繁体   English

如何在Android Studio 1.0中设置Robolectric

[英]How to setup Robolectric in Android Studio 1.0

I am a Android developer and a TDD passionate. 我是Android开发人员和TDD热衷。 Recently, I learned about a new testing framework, Robolectric, which seems to be far superior to the JUnit 3 solution Android Studio provides by default. 最近,我了解了一个新的测试框架Robolectric,它似乎远远优于Android Studio默认提供的JUnit 3解决方案。 I wanted to setup it, but after numerous tries, failures and java.lang.RuntimeException: Stub! 我想设置它,但经过多次尝试,失败和java.lang.RuntimeException: Stub! I achieved nothing. 我一无所获。

Here is my question: 这是我的问题:

How do I setup, step-by-step, the Robolectric testing framework on Andoird Studio 1.0? 如何在Andoird Studio 1.0上逐步设置Robolectric测试框架? Please note: 请注意:

  • I do not need vague ideas or hints. 我不需要模糊的想法或提示。 I need a complete solution. 我需要一个完整的解决方案
  • I can not provide any code from my previous tries, as it is useless and already deleted. 我无法提供之前尝试的任何代码,因为它没用,已经删除。

The setup of this framework is very problematic and has numerous issues among different versions of Android Studio and IntelliJ. 此框架的设置非常有问题,并且在不同版本的Android Studio和IntelliJ之间存在许多问题。 I browsed all of them, but to no avail. 我浏览了所有这些,但无济于事。 I need help from someone who succeded in using the framework on Android Studio 1.0. 我需要在Android Studio 1.0上成功使用该框架的人的帮助。

EDIT: 编辑:

Over those few months the setup process of Robolectric for Android Studio improved quite a bit, so before trying the below, 'long' approach, just try the official guide here ! 在那几个月Robolectric了解Android Studio建立的过程,提高了不少,所以尝试以下,“长”的方式之前,只要尝试官方指南在这里 :-) :-)


Ok, I managed to setup it! 好的,我设法安装了它! It is very tricky and not fully compatible with the newest Gradle 1.0.0, but it is working like a charm! 它非常棘手,并且与最新的Gradle 1.0.0不完全兼容,但它的工作就像一个魅力!

My solution is based mainly on this tutorial 我的解决方案主要基于本教程

So, your build.gradle file (the "inner" one, inside the project's folder) should look like this: 因此,您的build.gradle文件(项目文件夹中的“内部”文件)应如下所示:

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.14.1'
        classpath 'org.robolectric:robolectric-gradle-plugin:0.14.0'
    }
}

allprojects {
    repositories {
        mavenCentral()
        maven { url 'https://oss.sonatype.org/content/repositories/snapshots' }
    }
}

apply plugin: 'com.android.application'
apply plugin: 'robolectric'


android {
    compileSdkVersion 21
    buildToolsVersion "21.1.1"
    defaultConfig {
        applicationId '[your app id]'
        minSdkVersion 9
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }
    sourceSets {
        androidTest.setRoot('src/androidTest') // This one is important, make sure to avoid typos in it, or you will get empty tests
    }
    lintOptions {
        abortOnError false
        disable 'InvalidPackage'
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:appcompat-v7:21.0.2'

    // ================== TESTING LIBRARIES ======================
    androidTestCompile 'junit:junit:4.10'
    androidTestCompile 'org.robolectric:robolectric:2.4'
    androidTestCompile 'org.bouncycastle:bcprov-jdk15on:1.50'
}

robolectric {
    // configure the set of classes for JUnit tests
    include '**/*Test.class' //Make sure you call all your test classes according to this expression!!!

    // configure max heap size of the test JVM
    maxHeapSize = "2048m"
}

apply plugin: 'jacoco'

jacoco {
    toolVersion = "0.7.1.201405082137"
}

def coverageSourceDirs = [
        '../app/src/main/java'
]

task jacocoTestReport(type: JacocoReport, dependsOn: "testDebug") {
    group = "Reporting"

    description = "Generate Jacoco coverage reports"

    classDirectories = fileTree(
            dir: '../app/build/intermediates/classes/debug',
            excludes: ['**/R.class',
                       '**/R$*.class',
                       '**/*$ViewInjector*.*',
                       '**/BuildConfig.*',
                       '**/Manifest*.*']
    )

    additionalSourceDirs = files(coverageSourceDirs)
    sourceDirectories = files(coverageSourceDirs)
    executionData = files('../app/build/jacoco/testDebug.exec')

    reports {
        xml.enabled = true
        html.enabled = true
    }

}

It looks alot like the "outer" build.gradle file, but all this stuff has to be right here. 它看起来很像“外部”build.gradle文件,但所有这些东西都必须在这里。

Some of the elements my be unneeded here, but I did my best to cut it down to the core part. 我在这里不需要一些元素,但我尽力将其削减到核心部分。 After you so this, a Test class is created like this: 在这之后,创建一个Test类,如下所示:

import android.app.Activity;

import junit.framework.Assert;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;


@Config(emulateSdk = 18, reportSdk = 18) //Those are required as the framework does not yet support higher API levels
@RunWith(RobolectricTestRunner.class)
public class RoboDummyTest {

    @Test
    public void testActivityFound() {
        Activity activity = Robolectric.buildActivity(MainActivity.class).create().get();

        Assert.assertNotNull(activity);
    }
}

All data is stub of course :-) 所有数据当然是存根:-)

Finally, the tests are run by typing gradlew test into the terminal inside Android Studio. 最后,通过在Android Studio中的终端中输入gradlew test来运行gradlew test The results will be saved to a html file inside the build directory of your project. 结果将保存到项目build目录中的html文件中。

I hope this will be helpful to anyone planning on setting Robolectric with Android Studio 1.0. 我希望这对任何计划使用Android Studio 1.0设置Robolectric的人都有帮助。 Happy TDDing! 快乐TDDing!

EDIT: The author of the blog post I used to write the answer, Kvandermast, was as kind as to provide the below link to a repository containing a working example, updated every Android Studio update: https://github.com/kvandermast/my-robolectric-app 编辑:我曾经写过答案的博客文章的作者Kvandermast,提供以下链接到包含工作示例的存储库,更新每个Android Studio更新: https//github.com/kvandermast/我-robolectric-应用

I have tried out all different workarounds that I have been able to find, got some to work and some did not work at all. 我已经尝试了所有我能找到的不同的解决方法,一些工作,一些根本没用。

But yesterday I found one that actually worked without too much effort and does it so quite nicely: http://www.bignerdranch.com/blog/all-in-together-android-studio-gradle-and-robolectric/ 但是昨天我找到了一个实际上没有太多努力的工作,并且做得非常好: http//www.bignerdranch.com/blog/all-in-together-android-studio-gradle-and-robolectric/

This approach is based on a another gradle robolectric plugin, but it also includes an android studio plugin that handles the classpath problems in a neat way. 这种方法基于另一个gradle robolectric插件,但它还包括一个android studio插件,以一种简洁的方式处理类路径问题。

Best solution for this that I have found! 我找到的最佳解决方案! It works almost as if out-of-box. 它的工作方式几乎就像开箱即用一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM