Android Bundle简单单元测试不起作用 [英] Android Bundle simple unit test not working

查看:107
本文介绍了Android Bundle简单单元测试不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对android很陌生,试图了解bundle的工作原理.

I'm quite new to android and trying to understand how bundle works.

我被以下单元测试所阻止.有人可以解释一下为什么失败吗?

I get blocked by the following unit test. Can someone please explain why it fails ?

@Test
public void testBundle() throws Exception {
    Bundle bundle = new Bundle();
    String key = "hello";
    String value = "world";
    bundle.putString(key, value);
    Assert.assertEquals(value, bundle.getString(key));
}

junit.framework.ComparisonFailure: 
Expected :world
Actual   :null

推荐答案

JUnit测试在没有提供所有Android源代码的本地计算机上运行,​​而只是存根类(描述为

JUnit tests run on a local machine which doesn't have all the Android source code present, but just stub classes (described here). These stub classes allow you to compile your Android app against them (because their API is identical to the actual Android framework), but they do not contain any logic in order to make them "light".

默认情况下,如果您尝试调用任何存根方法,都会得到一个异常.像这样:

By default, if you attempt to invoke any of the stub methods you get an exception. Something like this:

public Bundle() {
    throw new RuntimeException("Stub!");
}

采用这种快速失败"方法是为了防止开发人员意外地对这些存根类运行代码,然后想知道为什么它不起作用.

this "fail fast" approach was employed in order to prevent developers from accidentally running their code against these stub classes and then wondering why it doesn't work.

但是,可以使用 build.gradle 中的此配置来更改此行为:

However, this behavior can be changed with this configuration in build.gradle:

android {
  ...
  testOptions {
    unitTests.returnDefaultValues = true
  }
}

这使存根方法返回默认值,而不是引发异常.

this makes the stub methods return default value instead of throwing exceptions.

您可能已启用了此功能,因此在运行JUnit测试时不会出现异常,但是 Bundle#getString()方法仅返回默认值( null ).

You probably have this feature enabled, therefore when you run your JUnit tests you don't get exception, but Bundle#getString() method just returns default value (which is null).

如果要测试具有Android框架相关性的代码,则应执行以下任一操作:

If you want to test code that has Android framework dependencies, you should do either of:

  1. 模拟这些依赖项(例如Mockito)
  2. 使用Robolectric运行测试
  3. 在Android设备上运行仪器测试

无论如何, unitTests.returnDefaultValues = true 是一个非常危险的功能,因为它使您的测试不可靠:某些测试可以通过,因为存根方法返回了默认值,但该功能将在真实设备上失败.关闭它.

In any case, unitTests.returnDefaultValues = true is a VERY DANGEROUS feature to use, because it makes your tests non-reliable: some test can pass because a default value was returned by stub method, but the functionality will fail on a real device. Turn it off.

这篇关于Android Bundle简单单元测试不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆