如何在Android Studio中使用测试绑定运行POJO测试?

时间:2013-09-10 00:48:39

标签: android unit-testing intellij-idea android-studio pojo

使用IntelliJ,我可以创建一个目录“test”,添加一些POJO测试文件并通过IDE运行它们。

使用Android Studio,我找不到办法做到这一点。我试图修改build.gradle,但我总是得到类找不到异常。

下一步是设置一个仅在测试期间加载一些Guice绑定的规则。

我的项目如下:

Project
  Module
  LibraryModule
    src
      main
        java/com/temp/...

      test
        java/com/temp/TestClass.java

TestClass.java:

package com.temp;

import org.junit.Before;
import org.junit.Test;


public class TestClass {

    @Before
    public void setup() throws Exception {

    }

    @Test
    public void testSomething() {
        //do something
    }

}

的build.gradle:

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

dependencies {
    instrumentTestCompile fileTree(dir: 'libs/test', include: '*.jar')
    compile fileTree(dir: 'libs', include: '*.jar')
    compile 'com.android.support:support-v4:13.0.0'
}

我得到错误:

Class not found: "com.temp.TestClass"

当我在IntelliJ中运行相同的项目时,我没有收到任何错误。任何提示都会有所帮助,谢谢!

1 个答案:

答案 0 :(得分:2)

完整答案(基于我在此处找到的内容:http://tryge.com/2013/02/28/android-gradle-build/

的build.gradle:

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

configurations {
    unitTestCompile.extendsFrom runtime
    unitTestRuntime.extendsFrom unitTestCompile
}

dependencies {
    unitTestCompile files("$project.buildDir/classes/release")
}

task unitTest(type: Test, dependsOn: assemble) {
    description = "run unit tests"
    testClassesDir = project.sourceSets.unitTest.output.classesDir
    classpath = project.sourceSets.unitTest.runtimeClasspath
}

check.dependsOn unitTest


dependencies {
    unitTestCompile fileTree(dir: 'libs/test', include: '*.jar')
    unitTestCompile fileTree(dir: 'libs', include: '*.jar') // redundant, but don't know how to fix it

    compile fileTree(dir: 'libs', include: '*.jar')
    compile 'com.android.support:support-v4:13.0.0'
}

然后,要为Guice添加测试绑定,请使您的测试类扩展为:

public class PojoTestCase {
    public PojoTestCase() {
        Guice.createInjector(new TestBindings()).injectMembers(this);
    }
}

运行方式:

./gradlew unitTest

此外,测试不会从Android Studio运行,但我现在很好。