【问题标题】:Cannot find context in class which extends TestCase在扩展 TestCase 的类中找不到上下文
【发布时间】:2016-12-28 12:30:37
【问题描述】:

我正在为 Android 应用程序类编写测试用例。但我无法找到获取此类上下文的方法。下面是我的测试用例类。

public class SplashScreenActivityTest extends TestCase {
    SplashScreenActivity splashScreenActivity;
    Context context;

    public void setUp() throws Exception {
        super.setUp();
        splashScreenActivity = new SplashScreenActivity();
    }

    public void testDeviceDetailsPost() throws Exception {
     //I need to access a method here which requires context
    }
}

我看了很多问题,但我无法理解他们的答案。

例如这个问题 Get context of test project in Android junit test case

【问题讨论】:

    标签: java android android-testing testcase


    【解决方案1】:

    你可以将实例变量context传递给需要它的方法,如下methodThatRequiresContext(context);

    我不完全确定你的困难是什么。

    【讨论】:

    • 上下文必须包含一个上下文,只是创建变量并将其传递给方法是行不通的。
    • like Context context = getContext();
    【解决方案2】:

    可以使用AndroidTestCase,这个类有getContext()方法;

    或者创建没有父类的类并将@RunWith(AndroidJUnit4.class) 添加到类头。并使用这个: InstrumentationRegistry.getTargetContext();

    提醒:我必须把这个测试类放到androidTest包中,因为这个类里面有集成测试。

    【讨论】:

    • AndroidTestCase 已弃用
    【解决方案3】:

    了解 Android 测试的良好起点。

    1. 培训Building effective unit tests(来自 Google 的官方文档)
    2. 存储库Android Testing Blueprint 包含不同类型测试的示例。

    【讨论】:

      猜你喜欢
      • 2011-03-22
      • 1970-01-01
      • 2021-12-14
      • 1970-01-01
      • 2017-02-24
      • 1970-01-01
      • 1970-01-01
      • 2022-08-23
      • 2019-12-06
      相关资源
      最近更新 更多