爲何要使用PowerMock
現現在比較流行的Mock工具如jMock 、EasyMock 、Mockito等都有一個共同的缺點:不能mock靜態、final、私有方法等。而PowerMock可以完美的彌補以上三個Mock工具的不足。
PowerMock簡介
PowerMock是一個擴展了其它如EasyMock等mock框架的、功能更增強大的框架。PowerMock使用一個自定義類加載器和字節碼操做來模擬靜態方法,構造函數,final類和方法,私有方法,去除靜態初始化器等等。經過使用自定義的類加載器,簡化採用的IDE或持續集成服務器不須要作任何改變。熟悉PowerMock支持的mock框架的開發人員會發現PowerMock很容易使用,由於對於靜態方法和構造器來講,整個的指望API是同樣的。PowerMock旨在用少許的方法和註解擴展示有的API來實現額外的功能。目前PowerMock支持EasyMock和Mockito。
PowerMock入門
PowerMock有兩個重要的註解:
–@RunWith(PowerMockRunner.class)
–@PrepareForTest( { YourClassWithEgStaticMethod.class })
若是你的測試用例裏沒有使用註解@PrepareForTest,那麼能夠不用加註解@RunWith(PowerMockRunner.class),反之亦然。當你須要使用PowerMock強大功能(Mock靜態、final、私有方法等)的時候,就須要加註解@PrepareForTest。服務器
PowerMock基本用法
(1) 普通Mock: Mock參數傳遞的對象
測試目標代碼:框架
public boolean callArgumentInstance(File file) { return file.exists(); }
測試用例代碼: 函數
@Test public void testCallArgumentInstance() { File file = PowerMockito.mock(File.class); ClassUnderTest underTest = new ClassUnderTest(); PowerMockito.when(file.exists()).thenReturn(true); Assert.assertTrue(underTest.callArgumentInstance(file)); }
說明:普通Mock不須要加@RunWith和@PrepareForTest註解。工具
(2) Mock方法內部new出來的對象測試
測試目標代碼:google
public class ClassUnderTest { public boolean callInternalInstance(String path) { File file = new File(path); return file.exists(); } }
測試用例代碼:spa
@RunWith(PowerMockRunner.class) public class TestClassUnderTest { @Test @PrepareForTest(ClassUnderTest.class) public void testCallInternalInstance() throws Exception { File file = PowerMockito.mock(File.class); ClassUnderTest underTest = new ClassUnderTest(); PowerMockito.whenNew(File.class).withArguments("bbb").thenReturn(file); PowerMockito.when(file.exists()).thenReturn(true); Assert.assertTrue(underTest.callInternalInstance("bbb")); } }
說明:當使用PowerMockito.whenNew方法時,必須加註解@PrepareForTest和@RunWith。註解@PrepareForTest裏寫的類是須要mock的new對象代碼所在的類。code
(3) Mock普通對象的final方法
測試目標代碼:orm
public class ClassUnderTest { public boolean callFinalMethod(ClassDependency refer) { return refer.isAlive(); } } public class ClassDependency { public final boolean isAlive() { // do something return false; } }
測試用例代碼:對象
@RunWith(PowerMockRunner.class) public class TestClassUnderTest { @Test @PrepareForTest(ClassDependency.class) public void testCallFinalMethod() { ClassDependency depencency = PowerMockito.mock(ClassDependency.class); ClassUnderTest underTest = new ClassUnderTest(); PowerMockito.when(depencency.isAlive()).thenReturn(true); Assert.assertTrue(underTest.callFinalMethod(depencency)); } }
說明: 當須要mock final方法的時候,必須加註解@PrepareForTest和@RunWith。註解@PrepareForTest裏寫的類是final方法所在的類。
(4) Mock普通類的靜態方法
測試目標代碼:
public class ClassUnderTest { public boolean callStaticMethod() { return ClassDependency.isExist(); } } public class ClassDependency { public static boolean isExist() { // do something return false; } }
測試用例代碼:
@RunWith(PowerMockRunner.class) public class TestClassUnderTest { @Test @PrepareForTest(ClassDependency.class) public void testCallStaticMethod() { ClassUnderTest underTest = new ClassUnderTest(); PowerMockito.mockStatic(ClassDependency.class); PowerMockito.when(ClassDependency.isExist()).thenReturn(true); Assert.assertTrue(underTest.callStaticMethod()); } }
說明:當須要mock靜態方法的時候,必須加註解@PrepareForTest和@RunWith。註解@PrepareForTest裏寫的類是靜態方法所在的類。
(5) Mock 私有方法
測試目標代碼:
public class ClassUnderTest { public boolean callPrivateMethod() { return isExist(); } private boolean isExist() { return false; } }
測試用例代碼:
@RunWith(PowerMockRunner.class) public class TestClassUnderTest { @Test @PrepareForTest(ClassUnderTest.class) public void testCallPrivateMethod() throws Exception { ClassUnderTest underTest = PowerMockito.mock(ClassUnderTest.class); PowerMockito.when(underTest.callPrivateMethod()).thenCallRealMethod(); PowerMockito.when(underTest, "isExist").thenReturn(true); Assert.assertTrue(underTest.callPrivateMethod()); } }
說明:和Mock普通方法同樣,只是須要加註解@PrepareForTest(ClassUnderTest.class),註解裏寫的類是私有方法所在的類。
項目中的使用示例:
private String validLstContainsCase(List<PlatformCase> caseLst, PlatformCase platformParam) { return msg; } private CustomerProductPlatform createCustomerProductPlatform(Long platformCaseId) { return param; } @Test @PrepareForTest(PlatformCaseManageServiceImpl.class) public void validLstContainsCase(){ try { PlatformCaseManageServiceImpl serviceImpl = PowerMockito.mock(PlatformCaseManageServiceImpl.class); // 模擬對象 List<PlatformCase> caseLst = new ArrayList<>(); PlatformCase plat = new PlatformCase(); caseLst.add(plat); PowerMockito.when(serviceImpl, "validLstContainsCase",caseLst,plat).thenReturn("test"); } catch (Exception e) { e.printStackTrace(); } } @Test @PrepareForTest(PlatformCaseManageServiceImpl.class) public void createCustomerProductPlatform(){ try { PlatformCaseManageServiceImpl serviceImpl = PowerMockito.mock(PlatformCaseManageServiceImpl.class); PowerMockito.when(serviceImpl, "createCustomerProductPlatform",12l).thenReturn("test"); } catch (Exception e) { e.printStackTrace(); } }
(6) Mock系統類的靜態和final方法
測試目標代碼:
public class ClassUnderTest { public boolean callSystemFinalMethod(String str) { return str.isEmpty(); } public String callSystemStaticMethod(String str) { return System.getProperty(str); } }
測試用例代碼:
@RunWith(PowerMockRunner.class) public class TestClassUnderTest { @Test @PrepareForTest(ClassUnderTest.class) public void testCallSystemStaticMethod() { ClassUnderTest underTest = new ClassUnderTest(); PowerMockito.mockStatic(System.class); PowerMockito.when(System.getProperty("aaa")).thenReturn("bbb"); Assert.assertEquals("bbb", underTest.callJDKStaticMethod("aaa")); } }
說明:和Mock普通對象的靜態方法、final方法同樣,只不過註解@PrepareForTest裏寫的類不同 ,註解裏寫的類是須要調用系統方法所在的類。
無所不能的PowerMock
(1) 驗證靜態方法:
PowerMockito.verifyStatic();
Static.firstStaticMethod(param);
(2) 擴展驗證:
PowerMockito.verifyStatic(Mockito.times(2)); // 被調用2次 Static.thirdStaticMethod(Mockito.anyInt()); // 以任何整數值被調用
(3) 更多的Mock方法
http://code.google.com/p/powermock/wiki/MockitoUsage13
PowerMock簡單實現原理• 當某個測試方法被註解@PrepareForTest標註之後,在運行測試用例時,會建立一個新org.powermock.core.classloader.MockClassLoader實例,而後加載該測試用例使用到的類(系統類除外)。• PowerMock會根據你的mock要求,去修改寫在註解@PrepareForTest裏的class文件(當前測試類會自動加入註解中),以知足特殊的mock需求。例如:去除final方法的final標識,在靜態方法的最前面加入本身的虛擬實現等。• 若是須要mock的是系統類的final方法和靜態方法,PowerMock不會直接修改系統類的class文件,而是修改調用系統類的class文件,以知足mock需求