Android Base64 编码和解码在单元测试中返回 null

2024-01-07

我正在尝试使用 Android 中的 Base64 编码字符串进行解码http://developer.android.com/reference/android/util/Base64.html http://developer.android.com/reference/android/util/Base64.html class.

encodeToString 和decode 方法都返回null,我不知道出了什么问题,这是我的解码代码:

// Should decode to "GRC"
String friendlyNameBase64Encoded = "R1JD";

// This returns null
byte[] friendlyNameByteArray = Base64.decode(friendlyNameBase64Encoded, Base64.DEFAULT);

// Fails with NullPointerException
String friendlyName = new String(friendlyNameByteArray, "UTF-8");

我正在运行 Android API 23.1.0


我在单元测试中遇到了同样的问题。我没有意识到我正在使用的 Base64 类是 Android API 的一部分,因此

您不能在常规 JUnit 测试中使用 android.util.Base64,它必须是 Instrumentation 测试。

但是,如果您确实希望将其作为单元测试,则可以使用 Apache Commons Base64 类。将其包含在 Gradle 构建中:

// https://mvnrepository.com/artifact/org.apache.commons/commons-collections4
compile group: 'org.apache.commons', name: 'commons-collections4', version: '4.1'

然后用法略有不同,

  • Base64.编码Base64String(字节[]二进制数据) http://commons.apache.org/proper/commons-codec/apidocs/org/apache/commons/codec/binary/Base64.html#encodeBase64String(byte%5B%5D)

  • Base64.解码Base64(字符串base64String) http://commons.apache.org/proper/commons-codec/apidocs/org/apache/commons/codec/binary/Base64.html#decodeBase64(java.lang.String)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Android Base64 编码和解码在单元测试中返回 null 的相关文章

随机推荐