我正在尝试使用 http://developer.android.com/reference/android/util/Base64.html 在 Android 中解码 Base64 编码的字符串类。
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'
然后用法略有不同,
关于java - Android Base64编解码单元测试返回null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33847781/