Android Base64 encode and decode return null in Unit Test

前端 未结 4 1473
失恋的感觉
失恋的感觉 2021-02-18 18:21

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

4条回答
  •  野的像风
    2021-02-18 18:36

    As discussed, android.util.Base64.decode is returning a null in test harness because of this setting in the build file:

    testOptions {
        unitTests.returnDefaultValues = true
    }
    

    To avoid including other libraries you could fall back on java.util.Base64, which is only available in Java8 and on Android 26 and above. If you already target 26+ then just switch to this method, but if you have to target earlier SDKs you could check for the null return and call a test-harness method instead:

    // Required because Android classes return null in desktop unit tests
    @TargetApi(26)
    private fun testHarnessDecode(s : String) : ByteArray {
        return java.util.Base64.getDecoder().decode(s)
    }
    

    I would rather do this than pull in additional library dependencies, but YMMV.

提交回复
热议问题