我正在尝试验证是否将特定的额外内容添加到 Intent 中,但在单元测试 Android 中,我的 Intent 始终为 null。我有以下需要测试的类:
public class TestClass extends SomeNotifier {
private Intent mIntent = new Intent("testintent");
public TestClassConstructor(Context context) {
super(context);
}
@Override
public void notifyChange() {
mIntent.putExtra("Key one", 22);
mIntent.putExtra("Key two", 23);
mIntent.putExtra("Key three", 24);
getContext().sendBroadcast(mIntent);
}
}
测试如下(我也尝试使用 mockIntent,但结果是一样的,extras 还是 null):
@RunWith(MockitoJUnitRunner.class)
public class TestClassTest {
@Mock
Context mMockContext;
@Test
public void sendBroadcastTest() {
ArgumentCaptor<Intent> argument = ArgumentCaptor.forClass(Intent.class);
TestClass testClassNotifier = new TestClass (mMockContext);
testClassNotifier.notifyChange();
verify(mMockContext).sendBroadcast(argument.capture());
Intent intent = argument.getValue();
//THE INTENT IS NULL
Assert.assertTrue(intent.hasExtra("Key one"));
}
}
您对我应该如何使这个测试起作用有什么建议吗? 提前致谢
最佳答案
默认情况下,
Intent
和其他 Android 运行时类(如 Context
)仅在物理 Android 手机和模拟器上可用。对于本地单元测试,您将获得运行时的 stub 版本,其中 Intent
等方法默认返回 null
。参见 this question寻求解释。
这意味着您当前的测试是针对 Intent
的 stub 版本进行验证,默认情况下它将为所有方法调用返回 null
。
有一些解决方法 - 您可以将测试转换为插桩单元测试,这意味着您必须在真实的手机或模拟器上运行它。或者,您可以用您控制的类包装 Intent
类。
也许最好的解决方案是使用类似 Robolectric 的框架.这将为您提供重要 Android 类(如 Intent
)的工作测试替身(称为影子),用于在您的 IDE 中运行的本地单元测试。
一旦您仔细安装了 Robolectric,您只需添加以下内容即可使您的测试正常进行:
@RunWith(RobolectricTestrunner.class)
public class TestClassTest {
另外,请确保您在 Android 上使用正确的 Mockito 依赖项:
testCompile 'org.mockito:mockito-core:2.8.9'
androidTestCompile 'org.mockito:mockito-android:2.8.9'
关于android - 单元测试 Android Mockito 中的 Intent extras,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46469049/