【问题标题】:Android - Mock method of Application during instrumented testAndroid - 仪器测试期间的应用程序模拟方法
【发布时间】:2018-04-23 12:28:55
【问题描述】:

假设我的应用程序类如下:

import android.app.Application;

public class MyApp extends Application {

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

}

我有一些用于测试 UI 的仪器测试。假设我有以下测试:

public class MyMainActivityTest {

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

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

我想在MyMainActivityTest 中模拟example() 方法,假设它应该返回Mock Test 而不是Test。怎么做?

【问题讨论】:

  • 为什么是-1?我的问题不清楚吗?
  • 不知道为什么它被否决了。几分钟后回答不好

标签: android testing mocking mockito android-espresso


【解决方案1】:

您应该创建扩展您的Application 类的类并将其放入测试文件夹中。

    public class MyTestApp extends MyApp {

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

然后在您的测试类上使用来自 Robolectric 库的 @Config 注释:

@Config(application = MyTestApp)

这应该适用于所有类型的测试,包括 Espresso UI 测试,如果不是,您可以尝试将自定义 TestRunner 与您的 TestApp 类一起使用,例如 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);
  }
}

然后把它放在你的 Test 类上: @RunWith(MyRunner.class)

【讨论】:

    猜你喜欢
    • 2023-01-21
    • 2020-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-04
    • 1970-01-01
    • 2011-08-25
    • 1970-01-01
    相关资源
    最近更新 更多