jok*_*kki 5 testing android android-intent robolectric
我可以使用Robolectric来测试一个Activity是否启动了一个带有Intent传递的特定Bundle的服务?答:是的!
我想编写一个基于Robolectric的测试,测试我的MainActivity启动时MyService使用特定数字传递了intent intent:
在"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);
}
Run Code Online (Sandbox Code Playgroud)
这是我的测试用例"MainActivityTest.java":
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
}
}
Run Code Online (Sandbox Code Playgroud)
所以,我的问题是: 我可以将Robolectric用于此目的吗?
我想我想出来了,见下面的答案......
测试用例不起作用,因为它报告"No intent extras!".使用调试器我注意到Intent.putExtras()在Robolectric环境中没有任何影响.在我的设备上运行应用程序时,i.mExtras(Intent.mExtras)属性被正确设置为Bundle引用.当我运行测试用例时null.我想这暗示我的问题的答案是"不",所以我应该放弃这个测试用例还是有办法完成这个测试?
编辑:更正了示例startMyActivity()方法以反映我实际遇到的问题:Intent.mExtras除非Bundle(?)中有一些内容,否则似乎没有填充属性.这与我使用调试器分析的实时Android环境不同.
我在呈现示例代码时并不完全准确!我已经更新了示例以显示我遇到问题的代码。
事实证明,与真实的 Android 环境相比,Robolectric 环境中 Intent 的管理方式有所不同。RobolectricIntent.mExtras不会被填充,Intent.putExtras()除非实际上有一些内容Bundle添加到Intent附加内容中。