我正在尝试将我的 Robolectric 测试与新的 Gradle Android 构建系统一起运行,但我一直无法访问我的主项目的资源。
我将构建拆分为两个单独的项目,以避免gradle 插件java
和android
gradle 插件之间发生冲突,因此目录结构大致如下所示:
.
├── build.gradle
├── settings.gradle
├── mainproject
│ ├── build
│ │ ├── classes
│ │ │ └── debug
│ ├── build.gradle
│ └── src
│ └── main
│ ├── AndroidManifest.xml
│ └── ...
└── test
├── build.gradle
└── src
└── test
└── java
└── ...
└── test
├── MainActivityTest.java
├── Runner.java
├── ServerTestCase.java
└── StatusFetcherTest.java
我build.gradle
的 intest/
目前看起来像这样:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.stanfy.android:gradle-plugin-java-robolectric:2.0'
}
}
apply plugin: 'java-robolectric'
repositories {...}
javarob {
packageName = 'com.example.mainproject'
}
test {
dependsOn ':mainproject:build'
scanForTestClasses = false
include "**/*Test.class"
// Oh, the humanity!
def srcDir = project(':mainproject').android.sourceSets.main.java.srcDirs.toArray()[0].getAbsolutePath()
workingDir srcDir.substring(0, srcDir.lastIndexOf('/'))
}
project(':mainproject').android.sourceSets.main.java.srcDirs.each {dir ->
def buildDir = dir.getAbsolutePath().split('/')
buildDir = (buildDir[0..(buildDir.length - 4)] + ['build', 'classes', 'debug']).join('/')
sourceSets.test.compileClasspath += files(buildDir)
sourceSets.test.runtimeClasspath += files(buildDir)
}
dependencies {
testCompile group: 'com.google.android', name: 'android', version: '4.1.1.4'
testCompile group: 'org.robolectric', name: 'robolectric', version: '2.0-alpha-3'
...
}
邪恶的类路径黑客允许我访问我的主项目的所有类,除了R
,它作为文件存在于构建目录中,但在任务.class
期间引发此错误:compileTestJava
/.../MainActivityTest.java:16: error: cannot find symbol
final String appName = activity.getResources().getString(R.string.app_name);
^
symbol: variable string
location: class R
1 error
:test:compileTestJava FAILED
必须有更好的方法来使用新的构建系统执行 Robolectric 测试,对吧?