对单例进行mock
单例类
public class PmModelHandler { // 包含要mock掉的成员变量 private static LogService logger = LogService.getInstance(); private static PmModelHandler instance = new PmModelHandler(); public static PmModelHandler getInstance() { return instance; } private PmModelHandler() { }
public void method(){
}
测试类
import java.util.Set; import org.junit.Before; 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; import com.zte.LogService; @RunWith(PowerMockRunner.class) @PrepareForTest({ PmModelHandler.class, LogService.class }) public class ModelUtilTest { private PmModelHandler handler; @Before public void setUp() throws Exception { LogService logService = PowerMockito .mock(LogService.class); PowerMockito.doNothing().when(logService, "writeLog", anyString()); PowerMockito.mockStatic(LogService.class); PowerMockito.doReturn(logService).when(LogService.class, "getInstance"); handler = PowerMockito.mock(PmModelHandler.class); PowerMockito.mockStatic(PmModelHandler.class); PowerMockito.doReturn(handler).when(PmModelHandler.class, "getInstance"); }
@Test
public void testMethod() throws Exception {
PowerMockito.doReturn(your obj).when(handler, "methodname", "input");
…………
原文:https://www.cnblogs.com/BrokenSwitch/p/9852592.html