使用基于级别的配置时,在Android Studio (IntelliJ)上运行简单的JUnit测试

时间:2022-02-08 05:07:06

I am using Android Studio/IntelliJ to build on an existing Android project and would like to add some simple JUnit unit tests. What is the right folder to add such tests on?

我正在使用Android Studio/IntelliJ来构建一个现有的Android项目,并想添加一些简单的JUnit单元测试。在什么文件夹中添加这样的测试?

The android Gradle plug-in defines a directory structure with src/main/java for the main source code and src/instrumentTest/java for Android tests.

android Gradle插件为android测试的主源代码和src/工具测试/java定义了一个带有src/main/java的目录结构。

Trying to add my JUnit tests in instrumentTest didn't work for me. I can run it as an Android test (that's what that directory seems for) but that's not what I'm looking for - I just want to run a simple JUnit test. I tried creating a JUnit run configuration for this Class but that also didn't work - I'm supposing because I'm using a directory that is flagged as Android Test instead of Source.

试图在工具测试中添加我的JUnit测试对我不起作用。我可以将它作为一个Android测试来运行(这个目录看起来就是这样的),但是这并不是我想要的——我只想运行一个简单的JUnit测试。我尝试为这个类创建一个JUnit运行配置,但它也不起作用——我假设是因为我使用了一个标记为Android Test而不是源代码的目录。

If I create a new source folder and marki it as such in Project Structure, this will get wiped next time IntelliJ refreshes the project configuration from the gradle build files.

如果我创建一个新的源文件夹并在项目结构中标记它,那么下次IntelliJ刷新来自gradle构建文件的项目配置时,它将被删除。

What is the more appropriate way of configuring JUnit tests in an gradle-based android project on IntelliJ? Which directory structure to use for this?

在IntelliJ上基于级别的android项目中配置JUnit测试的更合适的方式是什么?为此使用哪个目录结构?

6 个解决方案

#1


22  

As of Android Studio 1.1, the answer is now simple: http://tools.android.com/tech-docs/unit-testing-support

对于Android Studio 1.1,答案很简单:http://tools.android.com/tech-docs/unit-test -support

#2


36  

Normally, you can't. Welcome to the world of Android, where all tests must run on a device(except Robolectric).

通常情况下,你不能。欢迎来到Android世界,在那里所有的测试都必须在一个设备上运行(除了Robolectric)。

The main reason is that you don't actually have the framework's sources - even if you convince the IDE to run the test locally, you will immediately get a "Stub! Not implemented" exception. "Why?" you might wonder? Because the android.jar that the SDK gives you is actually all stubbed out - all the classes and methods are there but they all just throw an exception. It's there to provide an API but not there to give you any actual implementation.

主要原因是您实际上没有框架的源代码—即使您说服IDE在本地运行测试,您也会立即得到一个“存根”!没有实现“例外。“为什么?”你可能想知道吗?因为android。SDK提供的jar实际上都是存根化的——所有的类和方法都在那里,但是它们都抛出一个异常。它提供API,但不提供任何实际实现。

There's a wonderful project called Robolectric which implements a lot of the framework just so you can run meaningful tests. Coupled with a good mock framework (e.g., Mockito), it makes your job manageable.

有一个很棒的项目叫做Robolectric,它实现了很多框架,这样你才能运行有意义的测试。再加上一个好的模拟框架(例如Mockito),您的工作就可以管理了。

Gradle plugin: https://github.com/robolectric/robolectric-gradle-plugin

Gradle插件:https://github.com/robolectric/robolectric-gradle-plugin

#3


32  

Intro

Note that at the time of writing robolectric 2.4 is the latest version and has no support for appcompat v7 library. Support wil be added in robolectric 3.0 release (no ETA yet). Also ActionBar Sherlock can cause issues with robolectric.

注意,在编写robolectric 2.4时,它是最新的版本,不支持appcompat v7库。在robolectric 3.0版本中增加对wil的支持(目前还没有ETA)。动作条夏洛克也会引起罗埃特罗的问题。

To use Robolectric within Android Studio you have 2 options:

在Android Studio中使用Robolectric有两个选项:

(Option 1) - Running JUnit tests with Android Studio using a Java module

This technique uses a java module for all your tests with a dependency to your android module and a custom test runner with some magic:

该技术使用java模块进行所有测试,并依赖于您的android模块和具有一些魔力的自定义测试运行器:

Instructions can be found here: http://blog.blundellapps.com/how-to-run-robolectric-junit-tests-in-android-studio/

可以在这里找到说明:http://blog.blundellapps.com/howto -run-robolectric-junit-test -in-android- test -in-android-studio/。

Also check the link at the end of that post for running the tests from android studio.

还要检查文章末尾的链接,看看是否运行了android studio的测试。

(Option 2) - Running JUnit Tests with Android Studio using robolectric-gradle-plugin

I encountered a few issues setting up junit tests to run from gradle in Android Studio.

我在Android Studio中遇到了一些设置junit测试从gradle运行的问题。

This is a very basic sample project for running junit tests from a gradle based project in Android Studio: https://github.com/hanscappelle/android-studio-junit-robolectric This was tested with Android Studio 0.8.14, JUnit 4.10, robolectric gradle plugin 0.13+ and robolectric 2.3

这是一个非常基础的示例项目,用于运行Android Studio中的一个基于gradle的项目的junit测试:https://github.com/hanscappelle/android- junit-robolectric,这是用Android Studio 0.8.14、junit 4.10、robolectric gradle插件0.13+和robolectric 2.3进行测试的。

Buildscript (project/build.gradle)

The build script is the build.gradle file in the root of you project. There I had to add robolectric gradle plugin to classpath

构建脚本是构建。在您的项目的根目录文件。我不得不在类路径中添加robectric gradle插件

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.13.2'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath 'org.robolectric:robolectric-gradle-plugin:0.13.+'

    }
}

allprojects {
    repositories {
        jcenter()
    }
}

Project buildscript (App/build.gradle)

In the build script of your app module use the robolectric plugin, add robolectric config and add androidTestCompile dependencies.

在应用程序模块的构建脚本中,使用robolectric插件,添加robolectric配置并添加androidTestCompile依赖项。

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

android {
    // like any other project
}

robolectric {
    // configure the set of classes for JUnit tests
    include '**/*Test.class'
    exclude '**/espresso/**/*.class'

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

    // configure the test JVM arguments
    jvmArgs '-XX:MaxPermSize=512m', '-XX:-UseSplitVerifier'

    // configure whether failing tests should fail the build
    ignoreFailures true

    // use afterTest to listen to the test execution results
    afterTest { descriptor, result ->
        println "Executing test for {$descriptor.name} with result: ${result.resultType}"
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])

    androidTestCompile 'org.robolectric:robolectric:2.3'
    androidTestCompile 'junit:junit:4.10'
}

Create JUnit Test Classes

Now put the test classes in the default location (or update gradle config)

现在将测试类放在默认位置(或更新等级配置)

app/src/androidTest/java

And name your tests classes ending with Test (or again update config), extending junit.framework.TestCase and annotate test methods with @Test.

并将测试类命名为Test(或更新配置),扩展junit.framework.TestCase并使用@Test注释测试方法。

package be.hcpl.android.mytestedapplication;

import junit.framework.TestCase;
import org.junit.Test;

public class MainActivityTest extends TestCase {

    @Test
    public void testThatSucceeds(){
        // all OK
        assert true;
    }

    @Test
    public void testThatFails(){
        // all NOK
        assert false;
    }
}

Execute Tests

Next execute the tests using gradlew from command line (make it executable using chmod +x if needed)

接下来使用命令行中的gradlew执行测试(如果需要的话,使用chmod +x使其可执行)

./gradlew clean test

Sample output:

样例输出:

Executing test for {testThatSucceeds} with result: SUCCESS
Executing test for {testThatFails} with result: FAILURE

android.hcpl.be.mytestedapplication.MainActivityTest > testThatFails FAILED
    java.lang.AssertionError at MainActivityTest.java:21

2 tests completed, 1 failed                                  
There were failing tests. See the report at: file:///Users/hcpl/Development/git/MyTestedApplication/app/build/test-report/debug/index.html
:app:test                      

BUILD SUCCESSFUL

Troubleshooting

alternative source directories

Just like you can have your java source files somewhere else you can move your test source files. Just update gradle sourceSets config.

就像您可以将您的java源文件放在其他地方一样,您可以移动您的测试源文件。只需更新等级源代码配置。

    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
        }

        androidTest {
            setRoot('tests')
        }
    }

package org.junit does not exist

You forgot to add the junit test dependency in the app build script

您忘记在应用程序构建脚本中添加junit测试依赖项了

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])

    androidTestCompile 'org.robolectric:robolectric:2.3'
    androidTestCompile 'junit:junit:4.10'
}

java.lang.RuntimeException: Stub!

You're running this test with the run configurations from Android Studio instead of command line (Terminal tab in Android Studio). To run it from Android Studio you'll have to update the app.iml file to have the jdk entry listed at the bottom. See deckard-gradle example for details.

您正在使用Android Studio的运行配置运行这个测试,而不是命令行(Android Studio中的Terminal选项卡)。要从Android Studio运行它,您必须更新app.iml文件,以便在底部列出jdk条目。详细信息请参见deckard-gradle示例。

Complete error example:

完全错误的例子:

!!! JUnit version 3.8 or later expected:

java.lang.RuntimeException: Stub!
    at junit.runner.BaseTestRunner.<init>(BaseTestRunner.java:5)
    at junit.textui.TestRunner.<init>(TestRunner.java:54)
    at junit.textui.TestRunner.<init>(TestRunner.java:48)
    at junit.textui.TestRunner.<init>(TestRunner.java:41)
    at com.intellij.rt.execution.junit.JUnitStarter.junitVersionChecks(JUnitStarter.java:190)
    at com.intellij.rt.execution.junit.JUnitStarter.canWorkWithJUnitVersion(JUnitStarter.java:173)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:56)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)

ERROR: JAVA_HOME is set to an invalid directory

See this SO question for a solution. Add the below export to you bash profile:

看看这个问题的答案。将以下导出添加到您的bash概要:

export JAVA_HOME=`/usr/libexec/java_home -v 1.7`  

The complete error log:

完整的错误日志:

ERROR: JAVA_HOME is set to an invalid directory: export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation.

Test Class not found

If you want to run your tests from Android Studio Junit Test runner instead you'll have to expand the build.gradle file a little more so that android studio can find your compiled test classes:

如果您想从Android Studio Junit测试运行器运行您的测试,那么您必须扩展构建。等级文件稍微多一点,使android studio可以找到您编译的测试类:

sourceSets {
    testLocal {
        java.srcDir file('src/test/java')
        resources.srcDir file('src/test/resources')
    }
}

android {

    // tell Android studio that the instrumentTest source set is located in the unit test source set
    sourceSets {
        instrumentTest.setRoot('src/test')
    }
}

dependencies {

    // Dependencies for the `testLocal` task, make sure to list all your global dependencies here as well
    testLocalCompile 'junit:junit:4.11'
    testLocalCompile 'com.google.android:android:4.1.1.4'
    testLocalCompile 'org.robolectric:robolectric:2.3'

    // Android Studio doesn't recognize the `testLocal` task, so we define the same dependencies as above for instrumentTest
    // which is Android Studio's test task
    androidTestCompile 'junit:junit:4.11'
    androidTestCompile 'com.google.android:android:4.1.1.4'
    androidTestCompile 'org.robolectric:robolectric:2.3'

}

task localTest(type: Test, dependsOn: assemble) {
    testClassesDir = sourceSets.testLocal.output.classesDir

    android.sourceSets.main.java.srcDirs.each { dir ->
        def buildDir = dir.getAbsolutePath().split('/')
        buildDir =  (buildDir[0..(buildDir.length - 4)] + ['build', 'classes', 'debug']).join('/')

        sourceSets.testLocal.compileClasspath += files(buildDir)
        sourceSets.testLocal.runtimeClasspath += files(buildDir)
    }

    classpath = sourceSets.testLocal.runtimeClasspath
}

check.dependsOn localTest

from: http://kostyay.name/android-studio-robolectric-gradle-getting-work/

来自:http://kostyay.name/android-studio-robolectric-gradle-getting-work/

Some more resources

The best articles I found around this are:

我在这里找到的最好的文章是:

#4


4  

This is now supported in Android Studio starting with Android Gradle plugin 1.1.0, check this out:

这在Android Studio中得到了支持,从Android Gradle插件1.1.0开始,请查看:

https://developer.android.com/training/testing/unit-testing/local-unit-tests.html

https://developer.android.com/training/testing/unit-testing/local-unit-tests.html

Sample app with local unit tests on GitHub:

GitHub上带有本地单元测试的示例应用程序:

https://github.com/googlesamples/android-testing/tree/master/unittesting/BasicSample

https://github.com/googlesamples/android-testing/tree/master/unittesting/BasicSample

#5


1  

For Android Studio 1.2+ setting up a project for JUnit is pretty simple try to follow along this tutorial:

对于Android Studio 1.2+,为JUnit建立一个项目非常简单,请按照本教程进行:

This is the simplest part setting up a project for JUnit:

这是为JUnit建立项目的最简单的部分:

https://io2015codelabs.appspot.com/codelabs/android-studio-testing#1

https://io2015codelabs.appspot.com/codelabs/android-studio-testing # 1

Follow along the past link until "Running your tests"

跟随过去的链接直到“运行您的测试”

Now if you want to integrate with intrumentation test follow along from here:

现在,如果你想要集成喇叭测试,请从这里开始:

https://io2015codelabs.appspot.com/codelabs/android-studio-testing#6

https://io2015codelabs.appspot.com/codelabs/android-studio-testing # 6

#6


0  

Please see this tutorial from the Android Developers official site. This article also shows how to create mock-ups for your testing.

请参阅Android开发者官方网站的本教程。本文还展示了如何为您的测试创建模型。

By the way, you should note that the scope of the dependencies for simple JUnit test should be "testCompile".

顺便说一下,您应该注意到,简单JUnit测试依赖项的范围应该是“testCompile”。

#1


22  

As of Android Studio 1.1, the answer is now simple: http://tools.android.com/tech-docs/unit-testing-support

对于Android Studio 1.1,答案很简单:http://tools.android.com/tech-docs/unit-test -support

#2


36  

Normally, you can't. Welcome to the world of Android, where all tests must run on a device(except Robolectric).

通常情况下,你不能。欢迎来到Android世界,在那里所有的测试都必须在一个设备上运行(除了Robolectric)。

The main reason is that you don't actually have the framework's sources - even if you convince the IDE to run the test locally, you will immediately get a "Stub! Not implemented" exception. "Why?" you might wonder? Because the android.jar that the SDK gives you is actually all stubbed out - all the classes and methods are there but they all just throw an exception. It's there to provide an API but not there to give you any actual implementation.

主要原因是您实际上没有框架的源代码—即使您说服IDE在本地运行测试,您也会立即得到一个“存根”!没有实现“例外。“为什么?”你可能想知道吗?因为android。SDK提供的jar实际上都是存根化的——所有的类和方法都在那里,但是它们都抛出一个异常。它提供API,但不提供任何实际实现。

There's a wonderful project called Robolectric which implements a lot of the framework just so you can run meaningful tests. Coupled with a good mock framework (e.g., Mockito), it makes your job manageable.

有一个很棒的项目叫做Robolectric,它实现了很多框架,这样你才能运行有意义的测试。再加上一个好的模拟框架(例如Mockito),您的工作就可以管理了。

Gradle plugin: https://github.com/robolectric/robolectric-gradle-plugin

Gradle插件:https://github.com/robolectric/robolectric-gradle-plugin

#3


32  

Intro

Note that at the time of writing robolectric 2.4 is the latest version and has no support for appcompat v7 library. Support wil be added in robolectric 3.0 release (no ETA yet). Also ActionBar Sherlock can cause issues with robolectric.

注意,在编写robolectric 2.4时,它是最新的版本,不支持appcompat v7库。在robolectric 3.0版本中增加对wil的支持(目前还没有ETA)。动作条夏洛克也会引起罗埃特罗的问题。

To use Robolectric within Android Studio you have 2 options:

在Android Studio中使用Robolectric有两个选项:

(Option 1) - Running JUnit tests with Android Studio using a Java module

This technique uses a java module for all your tests with a dependency to your android module and a custom test runner with some magic:

该技术使用java模块进行所有测试,并依赖于您的android模块和具有一些魔力的自定义测试运行器:

Instructions can be found here: http://blog.blundellapps.com/how-to-run-robolectric-junit-tests-in-android-studio/

可以在这里找到说明:http://blog.blundellapps.com/howto -run-robolectric-junit-test -in-android- test -in-android-studio/。

Also check the link at the end of that post for running the tests from android studio.

还要检查文章末尾的链接,看看是否运行了android studio的测试。

(Option 2) - Running JUnit Tests with Android Studio using robolectric-gradle-plugin

I encountered a few issues setting up junit tests to run from gradle in Android Studio.

我在Android Studio中遇到了一些设置junit测试从gradle运行的问题。

This is a very basic sample project for running junit tests from a gradle based project in Android Studio: https://github.com/hanscappelle/android-studio-junit-robolectric This was tested with Android Studio 0.8.14, JUnit 4.10, robolectric gradle plugin 0.13+ and robolectric 2.3

这是一个非常基础的示例项目,用于运行Android Studio中的一个基于gradle的项目的junit测试:https://github.com/hanscappelle/android- junit-robolectric,这是用Android Studio 0.8.14、junit 4.10、robolectric gradle插件0.13+和robolectric 2.3进行测试的。

Buildscript (project/build.gradle)

The build script is the build.gradle file in the root of you project. There I had to add robolectric gradle plugin to classpath

构建脚本是构建。在您的项目的根目录文件。我不得不在类路径中添加robectric gradle插件

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.13.2'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath 'org.robolectric:robolectric-gradle-plugin:0.13.+'

    }
}

allprojects {
    repositories {
        jcenter()
    }
}

Project buildscript (App/build.gradle)

In the build script of your app module use the robolectric plugin, add robolectric config and add androidTestCompile dependencies.

在应用程序模块的构建脚本中,使用robolectric插件,添加robolectric配置并添加androidTestCompile依赖项。

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

android {
    // like any other project
}

robolectric {
    // configure the set of classes for JUnit tests
    include '**/*Test.class'
    exclude '**/espresso/**/*.class'

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

    // configure the test JVM arguments
    jvmArgs '-XX:MaxPermSize=512m', '-XX:-UseSplitVerifier'

    // configure whether failing tests should fail the build
    ignoreFailures true

    // use afterTest to listen to the test execution results
    afterTest { descriptor, result ->
        println "Executing test for {$descriptor.name} with result: ${result.resultType}"
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])

    androidTestCompile 'org.robolectric:robolectric:2.3'
    androidTestCompile 'junit:junit:4.10'
}

Create JUnit Test Classes

Now put the test classes in the default location (or update gradle config)

现在将测试类放在默认位置(或更新等级配置)

app/src/androidTest/java

And name your tests classes ending with Test (or again update config), extending junit.framework.TestCase and annotate test methods with @Test.

并将测试类命名为Test(或更新配置),扩展junit.framework.TestCase并使用@Test注释测试方法。

package be.hcpl.android.mytestedapplication;

import junit.framework.TestCase;
import org.junit.Test;

public class MainActivityTest extends TestCase {

    @Test
    public void testThatSucceeds(){
        // all OK
        assert true;
    }

    @Test
    public void testThatFails(){
        // all NOK
        assert false;
    }
}

Execute Tests

Next execute the tests using gradlew from command line (make it executable using chmod +x if needed)

接下来使用命令行中的gradlew执行测试(如果需要的话,使用chmod +x使其可执行)

./gradlew clean test

Sample output:

样例输出:

Executing test for {testThatSucceeds} with result: SUCCESS
Executing test for {testThatFails} with result: FAILURE

android.hcpl.be.mytestedapplication.MainActivityTest > testThatFails FAILED
    java.lang.AssertionError at MainActivityTest.java:21

2 tests completed, 1 failed                                  
There were failing tests. See the report at: file:///Users/hcpl/Development/git/MyTestedApplication/app/build/test-report/debug/index.html
:app:test                      

BUILD SUCCESSFUL

Troubleshooting

alternative source directories

Just like you can have your java source files somewhere else you can move your test source files. Just update gradle sourceSets config.

就像您可以将您的java源文件放在其他地方一样,您可以移动您的测试源文件。只需更新等级源代码配置。

    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
        }

        androidTest {
            setRoot('tests')
        }
    }

package org.junit does not exist

You forgot to add the junit test dependency in the app build script

您忘记在应用程序构建脚本中添加junit测试依赖项了

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])

    androidTestCompile 'org.robolectric:robolectric:2.3'
    androidTestCompile 'junit:junit:4.10'
}

java.lang.RuntimeException: Stub!

You're running this test with the run configurations from Android Studio instead of command line (Terminal tab in Android Studio). To run it from Android Studio you'll have to update the app.iml file to have the jdk entry listed at the bottom. See deckard-gradle example for details.

您正在使用Android Studio的运行配置运行这个测试,而不是命令行(Android Studio中的Terminal选项卡)。要从Android Studio运行它,您必须更新app.iml文件,以便在底部列出jdk条目。详细信息请参见deckard-gradle示例。

Complete error example:

完全错误的例子:

!!! JUnit version 3.8 or later expected:

java.lang.RuntimeException: Stub!
    at junit.runner.BaseTestRunner.<init>(BaseTestRunner.java:5)
    at junit.textui.TestRunner.<init>(TestRunner.java:54)
    at junit.textui.TestRunner.<init>(TestRunner.java:48)
    at junit.textui.TestRunner.<init>(TestRunner.java:41)
    at com.intellij.rt.execution.junit.JUnitStarter.junitVersionChecks(JUnitStarter.java:190)
    at com.intellij.rt.execution.junit.JUnitStarter.canWorkWithJUnitVersion(JUnitStarter.java:173)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:56)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)

ERROR: JAVA_HOME is set to an invalid directory

See this SO question for a solution. Add the below export to you bash profile:

看看这个问题的答案。将以下导出添加到您的bash概要:

export JAVA_HOME=`/usr/libexec/java_home -v 1.7`  

The complete error log:

完整的错误日志:

ERROR: JAVA_HOME is set to an invalid directory: export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation.

Test Class not found

If you want to run your tests from Android Studio Junit Test runner instead you'll have to expand the build.gradle file a little more so that android studio can find your compiled test classes:

如果您想从Android Studio Junit测试运行器运行您的测试,那么您必须扩展构建。等级文件稍微多一点,使android studio可以找到您编译的测试类:

sourceSets {
    testLocal {
        java.srcDir file('src/test/java')
        resources.srcDir file('src/test/resources')
    }
}

android {

    // tell Android studio that the instrumentTest source set is located in the unit test source set
    sourceSets {
        instrumentTest.setRoot('src/test')
    }
}

dependencies {

    // Dependencies for the `testLocal` task, make sure to list all your global dependencies here as well
    testLocalCompile 'junit:junit:4.11'
    testLocalCompile 'com.google.android:android:4.1.1.4'
    testLocalCompile 'org.robolectric:robolectric:2.3'

    // Android Studio doesn't recognize the `testLocal` task, so we define the same dependencies as above for instrumentTest
    // which is Android Studio's test task
    androidTestCompile 'junit:junit:4.11'
    androidTestCompile 'com.google.android:android:4.1.1.4'
    androidTestCompile 'org.robolectric:robolectric:2.3'

}

task localTest(type: Test, dependsOn: assemble) {
    testClassesDir = sourceSets.testLocal.output.classesDir

    android.sourceSets.main.java.srcDirs.each { dir ->
        def buildDir = dir.getAbsolutePath().split('/')
        buildDir =  (buildDir[0..(buildDir.length - 4)] + ['build', 'classes', 'debug']).join('/')

        sourceSets.testLocal.compileClasspath += files(buildDir)
        sourceSets.testLocal.runtimeClasspath += files(buildDir)
    }

    classpath = sourceSets.testLocal.runtimeClasspath
}

check.dependsOn localTest

from: http://kostyay.name/android-studio-robolectric-gradle-getting-work/

来自:http://kostyay.name/android-studio-robolectric-gradle-getting-work/

Some more resources

The best articles I found around this are:

我在这里找到的最好的文章是:

#4


4  

This is now supported in Android Studio starting with Android Gradle plugin 1.1.0, check this out:

这在Android Studio中得到了支持,从Android Gradle插件1.1.0开始,请查看:

https://developer.android.com/training/testing/unit-testing/local-unit-tests.html

https://developer.android.com/training/testing/unit-testing/local-unit-tests.html

Sample app with local unit tests on GitHub:

GitHub上带有本地单元测试的示例应用程序:

https://github.com/googlesamples/android-testing/tree/master/unittesting/BasicSample

https://github.com/googlesamples/android-testing/tree/master/unittesting/BasicSample

#5


1  

For Android Studio 1.2+ setting up a project for JUnit is pretty simple try to follow along this tutorial:

对于Android Studio 1.2+,为JUnit建立一个项目非常简单,请按照本教程进行:

This is the simplest part setting up a project for JUnit:

这是为JUnit建立项目的最简单的部分:

https://io2015codelabs.appspot.com/codelabs/android-studio-testing#1

https://io2015codelabs.appspot.com/codelabs/android-studio-testing # 1

Follow along the past link until "Running your tests"

跟随过去的链接直到“运行您的测试”

Now if you want to integrate with intrumentation test follow along from here:

现在,如果你想要集成喇叭测试,请从这里开始:

https://io2015codelabs.appspot.com/codelabs/android-studio-testing#6

https://io2015codelabs.appspot.com/codelabs/android-studio-testing # 6

#6


0  

Please see this tutorial from the Android Developers official site. This article also shows how to create mock-ups for your testing.

请参阅Android开发者官方网站的本教程。本文还展示了如何为您的测试创建模型。

By the way, you should note that the scope of the dependencies for simple JUnit test should be "testCompile".

顺便说一下,您应该注意到,简单JUnit测试依赖项的范围应该是“testCompile”。