Search code examples
powermockito

PowerMockito mockStatic gives MissingMethodInvocationException


I am trying to mockStatic method using PowerMockito , where I tried some options to mockStatic for a class, resulting in different exceptions.

@RunWith(PowerMockRunner.class)
@PrepareForTest({Base64.class})
public class BqClientFactoryTest {
    @Test
    public void testGetBigQueryClient() throws Exception {
        mockStatic(Base64.class);
        Base64.Decoder mockDecoder = mock(Base64.Decoder.class);
        when(Base64.getDecoder()).thenReturn(mockDecoder);

This resulted in org.mockito.exceptions.misusing.MissingMethodInvocationException:

I used another example like this

@RunWith(PowerMockRunner.class)
@PrepareForTest({Base64.class})
public class BqClientFactoryTest {
    @Test
    public void testGetBigQueryClient() throws Exception {
        mockStatic(Base64.class);
        Base64.Decoder mockDecoder = mock(Base64.Decoder.class);
        doReturn(mockDecoder).when(Base64.class, "getDecoder");

which gives me

org.mockito.exceptions.misusing.UnfinishedStubbingException: 
Unfinished stubbing detected here: 

If I use

BDDMockito.given(Base64.getDecoder()).willReturn(mockDecoder);

from Mocking static methods with Mockito , it still returns org.mockito.exceptions.misusing.MissingMethodInvocationException

I tried to check similar questions on SO, they haven't seemed to help. Any help resolving this is appreciated.


Solution

  • I solved it following this, all other solutions didn't work for me. It is difficult to search for this solution, since there are too many on SO on the same.

    PowerMockito mock single static method and return object inside another static method , PowerMock, mock a static method, THEN call real methods on all other statics

    @RunWith(PowerMockRunner.class)
    @PrepareForTest({Base64.class})
    public class BqClientFactoryTest {
        @Test
        public void testGetBigQueryClient() throws Exception {
            Base64.Decoder mockDecoder = mock(Base64.Decoder.class);
            stub(method(Base64.class, "getDecoder")).toReturn(mockDecoder);