Android Base64 encode and decode return null in Unit Test

匿名 (未验证) 提交于 2019-12-03 01:33:01

问题:

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

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"); 

I'm running Android API 23.1.0

回答1:

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

You can't use android.util.Base64 in a regular JUnit test, it must be an Instrumentation test.

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' 

And then slightly different usage,



回答2:

Follow up o android tutorials and unit test notes while you need just Unit tests without use of some android libs

In your case you're depending on android.Base64. I had similar issue and moving test classes from src/test -> src/androidTest worked. Those tests are run on virtual machine or real android device. I didn't notice the diff at the first look.



回答3:

You can use the Robolectric Runner

  1. Add the dependency in your build.gradle:

    testCompile 'org.robolectric:robolectric:X.X.X' 
  2. Add this line in your testing class:

    import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner;  @RunWith(RobolectricTestRunner.class) public class MyTestingClassTest {     ... } 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!