Search code examples
javaunit-testingjunitmockitopowermockito

Exception while using PowerMockito with static method


I want to mock a static method using PowerMockito,

public class DepedencyService {

    public static int getImportantValue() {
        return -4;
    }
}

public class Component {

    public int componentMethod() {
        return DepedencyService.getImportantValue();
    }
}

but it is giving me an exception.

import static org.testng.Assert.assertEquals;
import org.easymock.EasyMock;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest(DepedencyService.class)
public class ComponentTest {
    @Test
    public void testComponentMethod() {
        Component c = new Component();
        PowerMockito.mockStatic(DepedencyService.class);
        EasyMock.expect(DepedencyService.getImportantValue()).andReturn(1);
        assertEquals(1, c.componentMethod());
    }
}

The exception :-

java.lang.IllegalStateException: no last call on a mock available at org.easymock.EasyMock.getControlForLastCall(EasyMock.java:520) at org.easymock.EasyMock.expect(EasyMock.java:498)

Can anyone please help me? Why is this failing? I am new to PowerMockito and does not know what to do here!


Solution

  • You appear to be mixing mocking frameworks.

    You need to properly arrange the static dependencies before exercising the test

    Since PowerMockito is used to mock the static class then you should use Mockito to arrange the expected behavior

    For example

    @RunWith(PowerMockRunner.class)
    @PrepareForTest(DepedencyService.class)
    public class ComponentTest {
        @Test
        public void testComponentMethod() {
            //Arrange        
            int expected = 1;
            PowerMockito.mockStatic(DepedencyService.class);
            Mockito.when(DepedencyService.getImportantValue()).thenReturn(expected);
            Component subject = new Component();
    
            //Act
            int actual = subject.componentMethod();
    
            //Assert
            assertEquals(expected, actual);
        }
    }
    

    That said, I would advise not having your code tightly coupled to static dependencies. It makes for difficult to test code.