如何在Gradle中指定类路径排序

时间:2011-08-29 08:57:10

标签: unit-testing gradle robolectric

我需要在testRuntime配置中控制jar的顺序。

我必须确保robolectric-x.x.jar位于android.jar之前,否则我会得到可怕的RuntimeException(“Stub!”)。

我该怎么做?

2 个答案:

答案 0 :(得分:12)

这是我完整的 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);
    }

}

答案 1 :(得分:4)

这可能有效:

configurations { robo }

dependencies {
  robo ...
  testRuntime ...
}

sourceSets.test.runtimeClasspath = configurations.robo + sourceSets.test.runtimeClasspath