对单例进行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");

…………

有时会出现依赖的类无法初始化,而且mock不掉的时候,可使用注解屏蔽掉告警

@SuppressStaticInitializationFor("com.xxx.class")

05-11 15:39
查看更多