導航:首頁 > 方法技巧 > 方法中有新建對象如何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相關的資料

熱點內容
碳水化合物檢測方法 瀏覽:534
大數據教學方法論文 瀏覽:464
紅米手機開機鍵在哪裡設置方法 瀏覽:71
整數減分數最簡單的方法 瀏覽:657
14x37x5的簡便方法 瀏覽:329
定製衣櫃門套安裝方法 瀏覽:448
做衣服用電機方法視頻 瀏覽:485
比例是運用了什麼思想方法 瀏覽:421
樓梯彎頭度數計算方法 瀏覽:980
安全提籃使用方法 瀏覽:565
如何做作業的新方法 瀏覽:684
帝王菜的功效與作用及食用方法 瀏覽:230
基礎梁設計處理的計算方法 瀏覽:318
打啤酒的正確方法視頻 瀏覽:277
藍牙連接有線路由器的方法 瀏覽:970
學英語的方法和技巧答案 瀏覽:848
辦案區防撞軟包安裝方法 瀏覽:610
防雷接地裝置計算方法 瀏覽:636
臨床化學檢測多用什麼方法 瀏覽:279
催乳按摩方法圖片 瀏覽:263