Leader请求在做Junit测试的时辰,Mock掉各个办法之间的依附。这两天进修了下PowerMock的应用。
PowerMock是EasyMock的一个扩大,参加了static,final,private,以及constructor的Mock功能。然则PowerMock并没有持续EasyMock的一些测试功能,所以不克不及庖代EasyMock,而零丁应用。在很多时辰必必要PowerMock和EasyMock彼此连络,以及加上WhiteBox,才干更好实现测试。
1. 必不成少的一步:添加测试运行器@RunWith(PowerMockRunner.class),若是没有添加这个运行器,则应用的是默认的JUnit4.class。在PrepareForTest中参加测试class。@PrepareForTest(测试.class)
2. Construtor
public class A{
public void doA(){
B.doB();
}
}
public class B{
public B(){
System.out.println("can""t be here!");
}
}
测试classA中的doA办法:
@RunWith(PowerMockRunner.class)
@PrepareForTest({A.class})
public class ATest {
@Test
public void testdoA() throws Exception {
B mockB = PowerMock.createMock( B.class );
PowerMock.expectNew( B.class ).andReturn(mockB);
A testA = new A();
PowerMock.replayAll();
testA.doA();
PowerMock.verifyAll();
}
}
3.static
测试static办法的时辰必必要加上@PrepareForTest(静态办法.class),不然就会抛出java.lang.IllegalStateException: no last call on a mock available异常。若是有多个class,用{},例如@PrepareForTest({A.class,B.class})
public class A{
public void doA(){
B.doB();
}
}
public class B{
public static String doB() {
return ("can""t be here !");
}
}
测试classA中的doA办法:
@RunWith(PowerMockRunner.class)
@PrepareForTest({A.class, B.class})
public class ATest {
@Test
public void testdoA() throws Exception {
PowerMock.mockStatic( B.class );
EasyMock.expect(B.doB()).andReturn("Mocked !");
A testA = new A();
PowerMock.replayAll();
assertEquals("Mock not complete !", testA.doA(), "Mocked !");
PowerMock.verifyAll();
}
}
4.mock类中的Field
一个好的Field应当有getter和setter,然则代码中没有,我们也可以用WhiteBox来Mock掉Field。
public class A{
private String C;
public A(){
C = "Can""t be here !";
}
public String doA(){
return C;
}
}
测试A中的doA办法
@RunWith(PowerMockRunner.class)
@PrepareForTest({A.class, B.class})
public class ATest {
@Test
public void testdoA(){
A testA = new A();
String mockC = "Mocked !";
Whitebox.setInternalState( testA, "C", mockC );
assertEquals("Mock not complete !", testA.doA(), "Mocked !");
}
}