我想测试一个处理 Bundles 的方法.不过,我无法在测试环境中创建(非空)Bundle 对象。
给定以下代码:
Bundle bundle = new Bundle();
bundle.putString("key", "value");
boolean containsKey = bundle.containsKey("key");
containsKey
如果代码在应用程序上下文中执行,则为 true
,但如果在单元测试中执行,则为 false
。
我不明白为什么会这样,也不知道如何为我的测试创建 Bundle。
最佳答案
如果您的构建脚本包含如下内容:
testOptions {
unitTests.returnDefaultValues = true
}
这就是为什么即使您没有为 Bundle 类指定模拟,您的测试也不会失败的原因。
有几个选项可以解决这个问题:
使用 Mockito模拟 Bundle 类的模拟框架。不幸的是,您必须自己编写大量样板代码。例如,您可以使用此方法来模拟一个 bundle 对象,因此它会通过 getString 方法返回给您正确的值:
@NonNull private Bundle mockBundle() { final Map<String, String> fakeBundle = new HashMap<>(); Bundle bundle = mock(Bundle.class); doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { Object[] arguments = invocation.getArguments(); String key = ((String) arguments[0]); String value = ((String) arguments[1]); fakeBundle.put(key, value); return null; } }).when(bundle).putString(anyString(), anyString()); when(bundle.get(anyString())).thenAnswer(new Answer<String>() { @Override public String answer(InvocationOnMock invocation) throws Throwable { Object[] arguments = invocation.getArguments(); String key = ((String) arguments[0]); return fakeBundle.get(key); } }); return bundle; }
使用 Robolectric为您的单元测试提供某种影子类的框架。这允许您在单元测试中使用 Android 特定类,它们将正常运行。通过使用该框架,您的单元测试将正常运行,几乎无需您进行任何更改。
我想这是您最不希望看到的,但好吧,它是合格的。您可以使您的测试正常运行并在您的 Android 设备或模拟器上运行它。由于速度原因,我不推荐这种方式。在执行测试之前,您必须构建一个测试 apk,安装并运行。如果您要进行 TDD,这会非常慢。
关于java - 如何在单元测试中创建 Bundle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40382882/