Android Base64编码和解码在单元测试中返回null [英] Android Base64 encode and decode return null in Unit Test

查看:420
本文介绍了Android Base64编码和解码在单元测试中返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am attempting to decode a Base64 encoded string in Android using the http://developer.android.com/reference/android/util/Base64.html class.

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

Both the encodeToString and decode methods are returning null, and I have no idea what's wrong, here's my code for the decode:

// 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

I'm running Android API 23.1.0

推荐答案

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

I had the same problem in my unit tests. I didn't realize the Base64 class I'm using is a part of the Android API, therefore

你不能使用android.util.Base64 in一个常规的JUnit测试,它必须是一个Instrumentation测试。

但是,如果你真的想要它作为一个单元测试,你可以使用Apache Commons Base64而是改为。将它包含在Gradle构建中:

However, if you really want it as a unit test, you could use the Apache Commons Base64 class instead. Include it in Gradle build:

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

然后用法略有不同,

Base64。 decodeBase64(String base64String)

这篇关于Android Base64编码和解码在单元测试中返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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