Robolectric custom TestRunner does not work when starting with Gradle

I wanted to implement my own ApplicationShadow class to override the method getInstance(). I use Robolectric 3.0 and created a class MyRobolectricTestRunner, overriding the method createClassLoaderConfig()as follows:

public class MyRobolectricTestRunner extends RobolectricTestRunner {

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

    @Override
    public InstrumentationConfiguration createClassLoaderConfig() {
        InstrumentationConfiguration.Builder builder = InstrumentationConfiguration.newBuilder();
        builder.addInstrumentedClass(App.class.getName());
        return builder.build();
    }
}

The ShadowApp class is as follows:

@Implements(App.class)
public class ShadowApp{
    @RealObject private static App instance;

    public static void setAppInstance(App app){
        instance = app;
    }

    @Implementation
    public static App getInstance(){
        return instance;
    }
}

And the test that Runner uses is annotated as follows:

@RunWith(MyRobolectricTestRunner.class)
@Config(manifest=Config.NONE, shadows = {ShadowApp.class}, constants = BuildConfig.class, sdk = 21)
public class SomeShadowTest {

Now the problem is that when I run the test manually (by clicking "Run ..." for this only one test class), it passes without problems, but when I use the Gradle task "testDebug", test does not work, as if would the Shadow class be not used at all :(

Runner RobolectricGradleTestRunner, , ShadowApp ShadowApplication, getInstance()...: (

, ?

+4
1

, TestApplication, Robolectric .

, Test - , , .

. :

, com.example.robolectric

// src/main/java/com/example/robolectric
public class YourAplication extends Application {
   ...
}

// src/test/java/com/example/robolectric
/**
 * Robolectric uses class with name Test<ApplicationClassName> as test variant of the application
 * class. We use test application for API class injection so we need test version of this class.
 */
public class TestYourAplication extends YourAplication {
   ...
}
0

Source: https://habr.com/ru/post/1611164/


All Articles