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

熱點內容
輸入性假說研究方法 瀏覽:540
ph治療後復查的首選方法是 瀏覽:26
如何正確佩戴泳鏡和泳帽方法 瀏覽:462
60歲補身體最佳方法 瀏覽:12
地下室外止水螺桿計算方法 瀏覽:747
無土小麥苗種植方法 瀏覽:331
圖片裡面加字的方法 瀏覽:202
幼兒園小班怎麼上課語言教學方法 瀏覽:488
羊毛衫的簡單編織方法 瀏覽:339
如何上好一節課教學方法 瀏覽:188
教育科學研究方法及其實例 瀏覽:75
如何更好的學習掌握學習方法 瀏覽:561
鍛煉效果的評定方法 瀏覽:752
大腿前側扭到筋最快的解決方法 瀏覽:224
高泡洗車液使用方法 瀏覽:643
繁體字龜是用什麼方法簡化的 瀏覽:816
疥瘡治療的最好方法 瀏覽:740
hpv和hiv檢測方法 瀏覽:145
鍾南山治療方法 瀏覽:915
口腔設備管理的常用方法 瀏覽:488