Search code examples
androidjunitmockingbase64mockito

How to mock Base64 in Android?


I am writing a Unit test for a class that uses android.util.Base64 and I get this error:

java.lang.RuntimeException: Method encode in android.util.Base64 not mocked. See http://g.co/androidstudio/not-mocked for details.
at android.util.Base64.encode(Base64.java)

This is the code using the encode() method:

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
// [write some data to the stream]
byte[] base64Bytes = Base64.encode(byteArrayOutputStream.toByteArray(), Base64.DEFAULT);

Now I understand that I can't use Android library classes in my Unit tests. But how do I correctly mock Base64 so I can write a correct Unit test for my class?


Solution

  • With the newer versions of Mockito you can also mock static methods. No need for powermockito anymore:

    In gradle:

    testImplementation "org.mockito:mockito-inline:4.0.0"
    testImplementation "org.mockito.kotlin:mockito-kotlin:4.0.0"
    

    In kotlin:

    mockStatic(Base64::class.java)
    `when`(Base64.encode(any(), anyInt())).thenAnswer { invocation ->
        java.util.Base64.getMimeEncoder().encode(invocation.arguments[0] as ByteArray)
    }
    `when`(Base64.decode(anyString(), anyInt())).thenAnswer { invocation ->
        java.util.Base64.getMimeDecoder().decode(invocation.arguments[0] as String)
    }