Android - 仪表测试期间应用程序的模拟方法

标签 android testing mocking mockito android-espresso

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

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。怎么做?

最佳答案

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

    public class MyTestApp extends MyApp {

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

然后在您的测试类上使用 Robolectric 库中的 @Config 注解:

@Config(application = MyTestApp)

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

并将其放在您的测试类上: @RunWith(MyRunner.class)

关于Android - 仪表测试期间应用程序的模拟方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49981107/

相关文章:

ruby-on-rails-3 - 查找慢速 rspec 测试列表

具有私有(private)构造函数的 c# 模拟对象,通过静态工厂方法初始化

asp.net-mvc - 模拟 Asp.net-mvc Controller 上下文

android - 按钮无法解析为类型

java - 使用 Firebase 数据库跻身最佳玩家前十名

android - 从资源加载后位图宽度/高度不同

testing - WebAii 测试自动化框架死了吗?

testing - 有没有办法在 TestCafe 中指定动态报告文件名

android - 如何使用页面滑动 View 创建 Android 选项卡式样式

python - 通过用新方法替换模型类的实例方法来模拟它