Mock private methods
就是mock私有方法啦,學到這不難發現,我們其實大部分都是通過反射去完成單元測試的,但是在實際中,某個類中的私有方法,個人不建議使用反射來測試,因為有時候會覆蓋單元測試中的方法,那么下面我們就來舉個例子,來使用mock來模擬私有方法的測試。
模擬場景
假設我們按照人名去查找一個學生是否存在isExist(),如果存在就返回true,否則false,同時調用這個類中的私有的查找方法返回學生個數,如果存在返回1,不存在返回0
業務邏輯部分代碼比較簡單,具體代碼如下:
package com.rongrong.powermock.mockprivate; /** * @author rongrong * @version 1.0 * @description: * @date 2019/12/5 21:48 */ public class StudentPrivateService { public boolean isExist(String userName) { int count = checkExist(userName); if (count > 0) { return true; } else { throw new NullPointerException(); } } private int checkExist(String userName) { throw new UnsupportedOperationException(); } }
接着我們是powermock進行測試,使用上一篇文章中所學的AnSwer和spy方法來進行測試。
具體代碼如下:
package com.rongrong.powermock.mockprivate; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static junit.framework.TestCase.assertTrue; /** * @author rongrong * @version 1.0 * @description: * @date 2019/12/5 21:54 */ @RunWith(PowerMockRunner.class) @PrepareForTest(StudentPrivateService.class) public class TestStudentPrivateService { @Test public void testStudentPrivateService(){ StudentPrivateService studentPrivateService = PowerMockito.spy(new StudentPrivateService()); try { PowerMockito.doAnswer(new Answer<Integer>() { @Override public Integer answer(InvocationOnMock invocation) throws Throwable { String arg= (String) invocation.getArguments()[0]; if("rongrong".equals(arg)){ return 1; }else { return 0; } } }).when(studentPrivateService,"checkExist","rongrong"); boolean exist = studentPrivateService.isExist("rongrong"); assertTrue(exist); PowerMockito.verifyPrivate(studentPrivateService).invoke("checkExist","rongrong"); } catch (Exception e) { e.printStackTrace(); } } }
到此,整個powermock的學習就完成了,不得不說,powermock比想象中的強大的多。