【问题标题】:Android: how to get Context when testing with ActivityInstrumentationTestCase2?Android:使用 ActivityInstrumentationTestCase2 进行测试时如何获取上下文?
【发布时间】:2011-05-15 21:44:09
【问题描述】:

我正在 Android 中运行一个扩展 ActivityInstrumentationTestCase2 的 junit 测试。我正在使用它来启动一项活动。

活动使用应用程序对象的子类来获取一些参数。我从上下文中获取应用程序对象。

很遗憾,ActivityInstrumentationTestCase2 不提供对上下文的访问。有没有办法在获取活动之前访问上下文?

【问题讨论】:

    标签: android unit-testing


    【解决方案1】:

    您可以从检测对象中获取应用程序上下文:

    getInstrumentation().getTargetContext().getApplicationContext()
    

    【讨论】:

    • 哇哦!很棒的答案。
    【解决方案2】:

    为了能够使用setApplication() 注入应用程序,您应该使用ActivityUnitTestCase,因为它仅在此测试用例类中可用。

    默认情况下,ActivityUnitTestCase 创建一个隐藏的MockApplication 对象,用作被测应用程序。

    【讨论】:

    【解决方案3】:

    对于那些使用

    AndroidTestCase
    

    并且需要应用程序子类:

    MyApplication context = (MyApplication) getContext().getApplicationContext();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-26
      • 2018-12-24
      相关资源
      最近更新 更多