PowerMock學習(十)之Mock spy的使用
阿新 • • 發佈:2019-12-05
前言
回顧下之前學過的內容,會發現一點,如果在mock後不寫when和thenReturn去指定,即便是mock呼叫任何方法,什麼也不會做,也看不到什麼效果。
劃重點的時候來了,本身mock出來的物件是假的,再呼叫它的方法,一直都在“造假”。總結來說,就是一切都是假的,應了光良老師的那首歌,“童話裡都是騙人的”。
模擬場景
service中有一個寫資料到檔案的方法
service層
具體程式碼如下:
package com.rongrong.powermock.spies; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; /** * @description: * @author rongrong * @version 1.0 * @date 2019/12/4 22:45 */ public class FileService { /** * 寫入檔案及資料操 * @param text */ public void writeData(String text){ BufferedWriter bw = null; try { bw=new BufferedWriter(new FileWriter(System.getProperty("user.dir")+"/ronngrong.txt")); bw.write(text); bw.flush(); } catch (IOException e) { e.printStackTrace(); }finally { if(bw!=null){ try { bw.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
為了模擬呼叫方法後,啥也沒沒做這個現象,使用之前學過的方法,這裡我們不指定返回值(不加when和thenReturn),即人為干預
復現程式碼
使用之前學過的方法測試,具體示例程式碼如下:
@Test public void testFileService(){ FileService fileService = PowerMockito.mock(FileService.class); fileService.writeData("hellow,rongrong!!"); }
執行結果如下圖,並沒有新檔案生成,更別說寫入內容了
使用powerMock進行測試
採用 spy 的方式 mock一個物件,然後再呼叫其中的某個方法,它就會根據真實class 的所提供的方法來呼叫,具體示例程式碼如下:@Test public void testFileServiceWithSpy(){ FileService fileService = PowerMockito.spy(new FileService()); File file = new File(System.getProperty("user.dir") + "/ronngrong.txt"); fileService.writeData("hellow,RongRong!!"); assertTrue(file.exists()); }
直接執行這個測試用例,你會發現在專案根目錄下生成了一個新檔案,並且裡面寫入我們預期設定的內容,執行結果如下圖:
再來一看,最起碼我們執行能看到效果,即我知道呼叫方法後幹了些什麼!!