1

Assuming my Application class is like following:

import android.app.Application;

public class MyApp extends Application {

    public String example(){
        return "Test";
    }

}

I have some instrumented tests for testing UI. Assuming I have the following test:

public class MyMainActivityTest {

    @Rule
    public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<>(
            MainActivity.class);

    @Test
    public void firstTest(){
       onView(withId(R.id.textBt)).perform(click());
       // ...
    }
}

I want to mock example() method inside MyMainActivityTest, let's say that it should return Mock Test instead of Test. How to do it?

Bob
  • 381
  • 4
  • 12

1 Answers1

2

You should create Class which extends your Application class and put it into test folder.

    public class MyTestApp extends MyApp {

    public String example(){
        return "SuperTest";
    }
}

Then use @Config Annotation from Robolectric library over your test class:

@Config(application = MyTestApp)

This should work for all kind of tests including Espresso UI tests, if it isn't you can try to use custom TestRunner with your TestApp class like this:

public class MyRunner extends AndroidJUnitRunner {
  @Override
  public Application newApplication(ClassLoader cl, String className, Context context)
      throws Exception {
    return super.newApplication(cl, MyTestApp.class.getName(), context);
  }
}

And put this over your Test class: @RunWith(MyRunner.class)

Anton Kazakov
  • 2,740
  • 3
  • 23
  • 34