Wednesday 23 March 2016

PowerMock and TestNG mock static methods example

import org.mockito.Mock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.testng.PowerMockTestCase;
import org.testng.Assert;
import org.testng.annotations.Test;

import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.when;

@PrepareForTest(ClassStatic.class)
public class ClassStaticMockTest extends PowerMockTestCase {

    @Mock    
    public ClassStatic classStatic;

    @Test    
    public void mockGetValueVoid() throws Exception {
        mockStatic(ClassStatic.class);
        when(ClassStatic.getValue()).thenReturn("newValue");
        Assert.assertEquals(ClassStatic.getValue(), "newValue");
    }
}

class ClassStatic {
    static String getValue() {
        return "value";
    }
}