sto例子
如何mock系统类
给出了下面例子。把SystemUtils改成系统类System也是一样的,而且@PrepareForTest不用加System.class
package sample.com.sample_app;
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 static junit.framework.TestCase.assertEquals;
@RunWith(PowerMockRunner.class)
@PrepareForTest({SystemUtils.class})
public class FileUtilsTest {
@Test
public void generateName() {
PowerMockito.spy(SystemUtils.class);
PowerMockito.when(SystemUtils.currentTimeMillis()).thenReturn(100L);
String name = FileUtils.generateName();
assertEquals("100", name);
}
}
System
要添加
@RunWith(PowerMockRunner.class)
如果是系统类,不用添加到@PrepareForTest中,否则要添加
然后mock静态类
@Before
public void setup() {
PowerMockito.mockStatic(Files.class); // 1
}
然后在test方法里设置返回值
PowerMockito.when(System.currentTimeMillis()).thenReturn(999L);
System.out.println(System.currentTimeMillis());
Files实例
Files的案例,如下图