我需要在 testRuntime 配置中控制 jar 的顺序。
我必须确保 robolectric-xxjar 出现在 android.jar 之前,否则我会得到可怕的 RuntimeException("Stub!")。
我怎么做?
我需要在 testRuntime 配置中控制 jar 的顺序。
我必须确保 robolectric-xxjar 出现在 android.jar 之前,否则我会得到可怕的 RuntimeException("Stub!")。
我怎么做?
这是我完整的build.gradle,用于针对使用 RoboGuice 的 Android 应用程序运行 Robolectric 测试:
apply plugin: 'java'
androidJar = new File(System.getenv('ANDROID_HOME'), '/platforms/android-7/android.jar')
configurations { robo }
dependencies {
robo('com.pivotallabs:robolectric:1.0-RC1')
testCompile('org.roboguice:roboguice:1.1.2')
testCompile('junit:junit:4.8.2')
testCompile project (':app')
testCompile files(androidJar)
}
sourceSets.test.compileClasspath = configurations.robo + sourceSets.test.compileClasspath
sourceSets.test.runtimeClasspath = configurations.robo + sourceSets.test.runtimeClasspath
test {
excludes = ['**/MyRobolectricTestRunner.class']
}
我必须为测试运行器添加一个排除项,否则 Gradle 会抛出异常。
MyRobolectricTestRunner.java看起来像这样:
package com.acme.myapp;
import java.io.File;
import org.junit.runners.model.InitializationError;
import roboguice.application.RoboApplication;
import roboguice.inject.ContextScope;
import com.google.inject.Injector;
import com.xtremelabs.robolectric.Robolectric;
import com.xtremelabs.robolectric.RobolectricTestRunner;
public class MyRobolectricTestRunner extends RobolectricTestRunner {
public MyRobolectricTestRunner(Class<?> testClass) throws InitializationError {
// Tell Robolectric where to find AndroidManifest.xml and res/
super(testClass, new File("../app"));
}
/**
* Enable injection into tests as well...
*/
@Override
public void prepareTest(Object test) {
RoboApplication myApplication = (RoboApplication) Robolectric.application;
Injector injector = myApplication.getInjector();
ContextScope contextScope = injector.getInstance(ContextScope.class);
contextScope.enter(myApplication);
injector.injectMembers(test);
}
}
这是一个说明注入的示例测试:
package com.acme.myapp;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import roboguice.inject.InjectResource;
@RunWith(MyRobolectricTestRunner.class)
public class StringFormattingTest {
@InjectResource(R.string.info_pending_amount)
private String pendingAmountPattern;
@Test
public void testFormatInfoPendingAmount() {
String s = String.format(pendingAmountPattern, 20.0d, "EUR");
assertEquals("Only a part of your stake (20,00 EUR) was accepted", s);
}
}
这可能有效:
configurations { robo }
dependencies {
robo ...
testRuntime ...
}
sourceSets.test.runtimeClasspath = configurations.robo + sourceSets.test.runtimeClasspath