有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用Roboeletric和Gradle

我正在尝试设置Gradle以使用Roboelectric模拟框架运行Android测试

我有一个具有以下结构的Eclipse工作区:

MyApp
    src
    gen
    test
    ....

MyAppTest
    libs
    test (source folder linked to MyApp.test)
    ....

在Eclipse中手动配置构建路径,测试运行良好

如何在MyAppTest中配置Gradle构建脚本以使用Roboelectric在MyApp项目中运行测试


共 (1) 个答案

  1. # 1 楼答案

    基于这个solution我能够让这个工作正常进行

    总之,尝试将以下内容添加到build.gradle

    sourceSets {
        testLocal {
            java.srcDir file('src/test/java')
            resources.srcDir file('src/test/resources')
        }
    }
    
    dependencies {
        // Dependencies for your production code here.
        compile 'some.library'
    
        // localTest dependencies, including dependencies required by production code.
        testLocalCompile 'some.library'
        testLocalCompile 'junit:junit:4.11'
        testLocalCompile 'com.google.android:android:4.1.1.4'
        testLocalCompile 'org.robolectric:robolectric:2.2'
    }
    
    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
    

    别忘了把*Test.java改成@RunWith(RobolectricGradleTestRunner.class)

    public class RobolectricGradleTestRunner extends RobolectricTestRunner {
        public RobolectricGradleTestRunner(Class<?> testClass) throws InitializationError {
            super(testClass);
        }
    
        @Override
        protected AndroidManifest getAppManifest(Config config) {
            String pwd = YourApplication.class.getProtectionDomain().getCodeSource().getLocation().getPath();
            String root = pwd + "../../../src/main/";
    
            return new AndroidManifest(
                    Fs.fileFromPath(root + "AndroidManifest.xml"),
                    Fs.fileFromPath(root + "res"),
                    Fs.fileFromPath(root + "assets"));
        }
    }
    

    然后,您将能够通过gradle compileDebugJava localTest运行测试。如果我没记错的话,这将需要更新版本的gradle(可能是1.8或1.9)