Robolectric with Gradle: Resources not found

后端 未结 2 1400
忘掉有多难
忘掉有多难 2020-12-07 10:13

I\'m trying to run my Robolectric tests together with the new Gradle Android build system, but I\'m stuck at accessing the resources of my main project.

I split the

2条回答
  •  南方客
    南方客 (楼主)
    2020-12-07 10:47

    I was running across this same issue and this is what I came up with. Instead of creating a separate project for the tests, I created a source set for the Robolectric tests and added a new task that "check" would depend on. Using some of the code from your question, here are the relevant bits of the (working) build file:

    apply plugin: 'android'
    
    sourceSets {
        testLocal {
            java.srcDir file('src/test/java')
            resources.srcDir file('src/test/resources')
        }
    }
    
    dependencies {
        compile 'org.roboguice:roboguice:2.0'
        compile 'com.google.android:support-v4:r6'
    
        testLocalCompile 'junit:junit:4.8.2'
        testLocalCompile 'org.robolectric:robolectric:2.1'
        testLocalCompile 'com.google.android:android:4.0.1.2'
        testLocalCompile 'com.google.android:support-v4:r6'
        testLocalCompile 'org.roboguice:roboguice:2.0'
    }
    
    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
    

    I've included my dependencies block to point out that in order for me to get this up and going, I had to repeat all of my compile dependencies in my custom testLocal source set.

    Running gradle testLocal builds and runs just the tests inside of src/test/java, while running gradle check runs these tests in addition to those in the default android instrumentTest source set.

    Hope this helps!

提交回复
热议问题