1. 假如我们有下面的一个类:
Public class Demo {
public static void method1 {
...
}
public static void method2 {
...
}
public static void method3 {
...
}
}
然后我们想要为上面这个类写一个单元测试类,我们期待有测试类中mock掉method1和method2。
2. 下面就是我们定义的测试类:
@RunWith(PowerMockRunner.class)
@PrepareForTest({Demo.class})public class DemoTest {
@Before
public void setup() {
BasicConfigurator.configure();
PowerMock.mockStaticPartial(Demo.class, "method1", "method2");
EasyMock.expect(Demo.method1()).andReturn("method1").anyTimes();
EasyMock.expect(Demo.method2()).andReturn("method2").anyTimes();
PowerMock.replayAll();
}}
这里我们用到的PowerMock,EasyMock是来自于第三方包powermock-api-easymock-1.6.1,下面是maven对应的pom 依赖:
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-easymock</artifactId>
<scope>test</scope>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>org.easymock</groupId>
<artifactId>easymock</artifactId>
<scope>test</scope>
<version>3.3.1</version>
</dependency>