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 {