首页 > 代码库 > Mock

Mock

1,@PrepareForTest 出现时 @RunWith(PowerMockRunner.class) 必须出现.
2,代码中用到系统静态类 如:java.lang.System

public class SystemPropertyMockDemo {

public String getSystemProperty() throws IOException {

return System.getProperty("property");

}

}

@RunWith(PowerMockRunner.class)

@PrepareForTest({SystemPropertyMockDemo.class})//声明要Mock的类

public class SystemPropertyMockDemoTest {

@Test

public void demoOfFinalSystemClassMocking() throws Exception {

PowerMock.mockStatic(System.class);//Mock静态方法

EasyMock.expect(System.getProperty("property")).andReturn("my property");//录制Mock对象的静态方法

PowerMock.replayAll();//重放Mock对象

Assert.assertEquals("my property",

new SystemPropertyMockDemo().getSystemProperty());

PowerMock.verifyAll();//验证Mock对象

}

}

3,代码中用到用到另外一个类的私有方法。,@PrepareForTest中添加该类。

Mock