前言
回顧下之前學過的內容,會發現一點,如果在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()); }
直接運行這個測試用例,你會發現在項目根目錄下生成了一個新文件,並且里面寫入我們預期設定的內容,運行結果如下圖:
再來一看,最起碼我們運行能看到效果,即我知道調用方法后干了些什么!!