Reputation: 4181
I'm trying to setup Gradle to run Android test using Roboelectric mocking framework.
I have an Eclipse workspace with this structure:
MyApp
src
gen
test
....
MyAppTest
libs
test (source folder linked to MyApp.test)
....
Tests runs fine in Eclipse manually configuring build path.
How can I configure Gradle build scripts in MyAppTest to run tests in MyApp project using Roboelectric?
Upvotes: 1
Views: 548
Reputation: 1303
I was able to get this working based on this solution
In summary, try adding the following to your 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
Don't forget to alter your *Test.java
to @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"));
}
}
You will then be able to run your test via gradle compileDebugJava localTest
. If I remember correctly, this will require a newer version of gradle (perhaps 1.8 or 1.9)
Upvotes: 1