Android 使用Robolectric测试使用意向附加服务启动服务?

Android 使用Robolectric测试使用意向附加服务启动服务?,android,testing,android-intent,robolectric,Android,Testing,Android Intent,Robolectric,我是否可以使用Robolectric来测试某个活动是否启动了一个服务,并传递了一个特定的包回答:是 我想编写一个基于机器人分子的测试,测试我的main活动启动MyService时是否在intent extras中传递了一个特定的数字: 在“MainActivity.java”中,我有一个方法 public void startMyService() { Intent i = new Intent(this, MyService.class); Bundle intentExtras =

我是否可以使用Robolectric来测试某个活动是否启动了一个服务,并传递了一个特定的包回答:

我想编写一个基于机器人分子的测试,测试我的
main活动
启动
MyService
时是否在intent extras中传递了一个特定的数字:

在“MainActivity.java”中,我有一个方法

public void startMyService() {
  Intent i = new Intent(this, MyService.class);
  Bundle intentExtras = new Bundle();
  // TODO: Put magic number in the bundle
  i.putExtras(intentExtras);
  startService(i);
}
这是我的测试用例“MainActivityTest.java”:

所以,我的问题是: 我可以为此使用Robolectric吗?

我想我找到了答案,请参见下面的答案…

测试用例不起作用,因为它报告“无意图附加!”。使用调试器,我注意到Intent.putExtras()在Robolectric环境中没有效果。在设备上运行应用程序时,
i.mExtras
Intent.mExtras
)属性已正确设置为捆绑引用。当我运行测试用例时,它是
null
。我想这暗示我的问题的答案是“否”,所以我应该放弃这个测试用例,还是有任何方法来完成这个测试


编辑:更正了示例
startMyActivity()
方法,以反映我实际遇到的问题:似乎
意图。除非
捆绑包中有一些内容,否则不会填充mExtras
属性(?)。这与我使用调试器分析的实时Android环境不同。

我在演示示例代码时并不完全准确!我已经更新了示例,以显示我遇到问题的代码


结果表明,与真实的安卓环境相比,机器人分子环境中意图的管理方式有所不同。使用机器人分子
Intent.mExtras
不会被
Intent.putExtras()
填充,除非
包中确实有一些内容作为额外内容添加到
Intent
中。

有趣。我认为默认情况下Robolectric使用的是API16 AOSP。您正在调试的Android版本是什么?你能把`@Config{emulateSdk=}添加到你的测试中吗?我只是想知道它是否是Android版本或RobolectricHi Eugen的特定版本,谢谢你的提示。我正在为应用程序使用
targetSdkVersion 19
。我尝试了
emulateSdk={16,18,21}
进行测试,但结果总是一样的:如果我使用一个新的
进行
Intent.putExtras()
,但我没有向其中添加任何数据,那么
Intent.mExtras
在机器人分子环境中保持
null
。“AOSP”代表什么?…将
19
添加到(Robolectric)模拟SDK集合中。AOSP是Android开源项目让我检查一下Robolectric源代码:)
import ...

@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class)
public class MainActivityTest extends TestCase {
  @Override
  protected void setUp() throws Exception {
    super.setUp();
  }

  @Override
  protected void tearDown() throws Exception {
    super.tearDown();
  }

  @Test
  public void testShallPassMagicNumberToMyService() {
    MainActivity activityUnderTest = Robolectric.setupActivity(MainActivity.class);
    activityUnderTest.startMyService();

    Intent receivedIntent = shadowOf(activityUnderTest).getNextStartedService();

    assertNotNull("No intents received by test case!", receivedIntent);

    Bundle intentExtras = receivedIntent.getExtras();
    assertNotNull("No intent extras!", intentExtras);

    long receivedMagicNumber = intentExtras.
            getLong(MyService.INTENT_ARGUMENT_MAGIC_NUMBER);

    assertFalse("Magic number is not included with the intent extras!",
            (receivedMagicNumber == 0L));  // Zero is default if no 'long' was put in the extras
  }
}