導航:首頁 > 方法技巧 > 方法中有新建對象如何mock

方法中有新建對象如何mock

發布時間:2023-06-10 18:24:09

A. 怎麼mockito方法的內部對象

怎麼mockito方法的內部對象?Mockito是一個針對Java的mocking框架。它與EasyMock和jMock很相似,但是通過在執行後校驗什麼已經被調用,它消除了對期望行為(expectations)的需要。其它的mocking庫需要你在執行前記錄期望行為(expectations),而這導致了醜陋的初始化代碼。下文為轉載,但原文有問題,錯誤的地方特地標紅了

Introction
Code in which new objects are created can be difficult to test. There are a number of patterns for doing this; two of them are discussed here. Both of these patterns may require rearranging your code a little, to make it more testable. Writing code that's easily testable is a good thing to be doing, regardless of which mocking framework you end up using.

Details
Pattern 1 involves factoring uses of new into one-line methods, then using a Mockito spy. This is the simpler of the two patterns. Pattern 2 involves factoring uses of new into a separate class and injecting it. It's a little more work, but it can be more powerful. The new calls that you want to factor out (using either pattern) are those where an object is created, that you are likely to want to mock. It is recommended that you use one or other of these patterns, whenever you find yourself writing new, on a class that's in your code base (as opposed to a JDK class or a class from a third party library).

B. 使用Powermock對私有方法進行mock

 團譽宏 在public方法中往往會調用一些private方法,如果private方法很復雜,我們就需要處理很多方法的mock。如果這時只想要測試public方法,並不想關注private方法的邏輯,那麼就需要虛歷對private方法進行mock。下面我們簡單介紹下如何通過Powermock來對私有方法進行mock。

被測試類:

  此類中包含一個public方法mockPrivateFunc,裡面調用了private方法privateFunc。當前我們想要測試該public方法,並且不想進入private方法執行,那麼就需要對該塌冊私有方法進行模擬。

測試類:

  1、由於是對本類的私有方法進行模擬,所以需要在PrepareForTest後面加上MockPrivateClass,同時需要使用spy來模擬一個對象。
  2、 使用下面方式來模擬私有方法:

  如果私有方法存在參數,則同樣的需要在私有方法名後面帶上同樣個數及類型的參數,其方法原型為:

  3、使用verifyPrivate來驗證私有方法被調用,其例如下:

  verifyPrivate的參數為mock的對象,及驗證模式(可選),invoke參數為要驗證的私有方法名稱及相應參數。

C. 如何mock靜態方法

因為Mockito使用繼承的方式實現mock的,用CGLIB生成mock對象代替真實的對象進行執行,為了mock實例的方法,你可以在subclass中覆蓋它,而static方法是不能被子類覆蓋的,所以Mockito不能mock靜態方法。
但PowerMock可以mock靜態方法,因為它直接在bytecode上工作,類似這樣:
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.moles.testng.PowerMockTestCase;
import org.testng.Assert;
import org.testng.annotations.Test;
@PrepareForTest(AbstractAnimal.class)
public class AbstractAnimalTest extends PowerMockTestCase {

閱讀全文

與方法中有新建對象如何mock相關的資料

熱點內容
鯉魚河魚鑒別方法 瀏覽:532
福彩組三必中技巧方法 瀏覽:130
兒童存食有什麼方法 瀏覽:402
谷丙轉氨酶高治療方法 瀏覽:309
宏基投影連接方法 瀏覽:578
耳朵流黃水有什麼方法 瀏覽:812
明星防身訓練方法視頻 瀏覽:551
閉經用飲食保健的方法來治療 瀏覽:820
工資計算方法2015 瀏覽:436
粘土手工作品簡單製作方法 瀏覽:316
白花草的功效與食用方法 瀏覽:41
科技製作學生小發明超簡單方法 瀏覽:239
嘉寶果樹盆栽快速生長的方法 瀏覽:246
職位評價方法簡單 瀏覽:540
新冠常用疫苗接種方法 瀏覽:463
氣象站相對濕度的測量方法 瀏覽:29
梅毒檢測滴度與定量是兩種方法嗎 瀏覽:971
論文人類進化研究方法 瀏覽:394
小金魚公母的鑒別方法 瀏覽:814
扭腳腕有什麼好處和鍛煉方法 瀏覽:357