3

I have an image loader class and i wanted to test some static methods in it. Since Mockito does not support static methods i switched to Power Mockito. However the static method i am testing has a method call

 Base64.encodeToString(byteArray, Base64.DEFAULT);

To mock this i am using mockStatic method as below.

 PowerMockito.mockStatic(Base64.class);

But Android studio is returning me still returning me an error as below.

org.powermock.api.mockito.ClassNotPreparedException: The class android.util.Base64 not prepared for test. To prepare this class, add class to the '@PrepareForTest' annotation.

Below is my complete code.

@RunWith(PowerMockRunner.class)
@PrepareForTest({Base64.class})
public class ImageLoaderTest  {
@Test
   public void testConvertBitmap(){
    byte[] array = new byte[20];
    PowerMockito.mockStatic(Base64.class);
    PowerMockito.when(Base64.encodeToString(array, Base64.DEFAULT)).thenReturn("asdfghjkl");
    Bitmap mockedBitmap= PowerMockito.mock(Bitmap.class);
    String output = ImageLoaderUtils.convertBitmapToBase64(mockedBitmap);
    assert (!output.isEmpty());
}

}

Gradle dependencies

testCompile 'junit:junit:4.12'
testCompile 'org.powermock:powermock:1.6.5'
testCompile 'org.powermock:powermock-module-junit4:1.6.5'
testCompile 'org.powermock:powermock-api-mockito:1.6.5'
Ajith M A
  • 3,838
  • 3
  • 32
  • 55

1 Answers1

0

Though I don't know for sure, Android Studio may use the system classloader for Android classes, which would require you to use the same workarounds as for system classes.

Behind the scenes, Powermock uses a special classloader to rewrite the classes you prepare in such a way that Mockito or EasyMock can stub/verify private/static/final methods, whereas without special classloading Mockito and EasyMock normally rely on proxy subclasses that limit you to visible overridable instance methods. However, it's not possible to overwrite classes loaded by the system classloader, because the official implementations have already been loaded and cannot be replaced or augmented. Powermock instead has you prepare/rewrite the classes that interact with the system class, so the calls can be intercepted and redirected to your chosen mocking framework.

Also, though it seems to be just a matter of terminology here, you say you want to "test some static methods" and that "Mockito does not support static methods". You can use Mockito while testing static methods, but you can't use Mockito to verify or stub (replace the implementation of) static methods as you do with Base64.encodeToString; that's where you need PowerMock, as you do here. Be careful to never mock the system under test, or else you may test your mocked behavior without ever actually testing any real system.

Jeff Bowman
  • 90,959
  • 16
  • 217
  • 251