2013-05-18 8 views
3

с v2.0 robolectric и проектом на основе градита. Я столкнулся с проблемой отсутствия RobolectricContext для бегуна. Он работает с testCompile группы: 'org.robolectric', название: 'robolectric', версия: '2,0-альфа-2'RobolectricContext отсутствует для проекта, основанного на граде

и не с группы testCompile: 'org.robolectric', имя: 'robolectric' версия: «2,0»

у меня есть ощущение, что моя проблема заключается в моем Gradle файле сборки, но я не нашел способ исправить это пока:

apply plugin : 'java-robolectric' 
apply plugin : 'idea' 

// get 'java-robolectric' from Maven Central 
buildscript { 
    repositories { 
    mavenCentral() 
    } 
    dependencies { 
    // use version 2.0 for Robolectric 2.0 
    classpath group: 'com.stanfy.android', name: 'gradle-plugin-java-robolectric', version: '2.0' 
    } 
} 
sourceSets { 
    main { 
     java { 
      srcDir 'src/java' 
     } 
    } 
} 

version = '0.9' 

javarob { 
    packageName = 'org.ligi.androidhelper' 
} 

test { 
    scanForTestClasses = false 
    include "**/*Test.class" 
} 

repositories { 
    mavenCentral() 
} 

test { 
    afterTest { desc, result -> 
     println "Executing test ${desc.name} [${desc.className}] with result: ${result.resultType}" 
    } 
} 

dependencies { 
    compile fileTree(dir : 'libs', include : '*.jar') 

    testCompile group: 'junit', name: 'junit', version: '4.10' 
    testCompile group: 'org.mockito', name: 'mockito-core', version: '1.8.0' 

    compile group: 'com.google.android', name: 'android', version: '4.1.1.4' 
    testCompile group: 'org.robolectric', name: 'robolectric', version: '2.0' 
} 

, что это ошибка, я получаю:

[email protected]:~/git/AndroidHelper$ gradle test 
:compileJava UP-TO-DATE 
:processResources UP-TO-DATE 
:classes UP-TO-DATE 
:compileTestJava UP-TO-DATE 
:processTestResources UP-TO-DATE 
:testClasses UP-TO-DATE 
:test 
Executing test classMethod [org.ligi.androidhelper.test.CheckBoxHelperTest] with result: FAILURE 

org.ligi.androidhelper.test.CheckBoxHelperTest > classMethod FAILED 
    java.lang.RuntimeException 
     Caused by: java.lang.RuntimeException 
Executing test classMethod [org.ligi.androidhelper.test.BitmapHelperTest] with result: FAILURE 

org.ligi.androidhelper.test.BitmapHelperTest > classMethod FAILED 
    java.lang.RuntimeException 
     Caused by: java.lang.RuntimeException 

2 tests completed, 2 failed 
:test FAILED 

FAILURE: Build failed with an exception. 

* What went wrong: 
Execution failed for task ':test'. 
> There were failing tests. See the report at: file:///home/ligi/git/AndroidHelper/build/reports/tests/index.html 

* Try: 
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. 

BUILD FAILED 

Total time: 11.723 secs 

Полный источник здесь: https://github.com/ligi/AndroidHelper

+0

RobolectricContext не доступен в источнике Robolectric 2.0 больше. В настоящее время я ищу хороший способ миграции. – keyboardsurfer

ответ

0

обходной путь не для удаления Runner.java - потому что он всегда получает автоматически генерируется robolectric Gradle плагин с неисправным кодом (использование RobolectricContex). Хитрость заключается в том, чтобы изменить этот файл - даже если вы на самом деле не намерены использовать его - мой выглядит следующим образом:

import java.io.File; 
import org.junit.runners.model.InitializationError; 
import org.robolectric.AndroidManifest; 
import org.robolectric.RobolectricTestRunner; 

/**              
* Use this runner instead of RobolectricTestRunner with @RunWith annotation. 
*/ 
public class Runner extends RobolectricTestRunner { 

    public Runner(final Class<?> testClass) throws InitializationError { 
     super(testClass); 
    } 

} 
2

RobolectricContext Класс не требуется больше. Кроме того, в Robolectric 2.0 этого не существует. Вы можете просто переопределить методы из RobolectricTestRunner.

Например, нахождение AndroidManifest.xml может быть достигнута с помощью:

@Override 
protected AndroidManifest createAppManifest(FsFile manifestFile) { 
    if (!manifestFile.exists()) { 
    manifestFile = Fs.fileFromPath("pathToMy/AndroidManifest.xml"); 
    } 
    return super.createAppManifest(manifestFile); 
} 
+1

Или, что еще проще, используйте аннотацию @Config (manifest = "MyFile.xml") или создайте файл с именем org.robolectric.Config.properties. Не нужно будет расширять RobolectricTestRunner дольше. – Xian

+0

Спасибо за ответы, но я не хочу использовать пользовательский Runner - на самом деле я использую по умолчанию: import org.robolectric.RobolectricTestRunner; @RunWith (RobolectricTestRunner.class) Но Runner.java генерируется с кодом ошибки, несмотря ни на что. – ligi