天天看點

mockito中兩種部分mock的實作,spy、callRealMethod

什麼是類的部分mock(partial mock)?

A:部分mock是說一個類的方法有些是實際調用,有些是使用mockito的stubbing(樁實作)。

為什麼需要部分mock?

A:當需要測試一個組合方法(一個方法需要其它多個方法協作)的時候,某個葉子方法(隻供别人調用,自己不依賴其它反複)已經被測試過,我們其實不需要再次測試這個葉子方法,so,讓葉子打樁實作傳回結果,上層方法實際調用并測試。

mockito實作部分mock的兩種方式:spy和callRealMethod()

Spy類就可以滿足我們的要求。如果一個方法定制了傳回值或者異常,那麼就會按照定制的方式被調用執行;如果一個方法沒被定制,那麼調用的就是真實類的方法。

如果我們定制了一個方法A後,再下一個測試方法中又想調用真實方法,那麼隻需在方法A被調用前,調用Mockito.reset(spyObject);就行了。

輸出為:

要注意的是,對Spy對象的方法定制有時需要用另一種方法:

===============================================================================

Importantgotcha on spying real objects!

Sometimes it's impossible to usewhen(Object) for stubbing spies. Example:

List list = new LinkedList();

List spy = spy(list);

//Impossible: real method is called so spy.get(0) throwsIndexOutOfBoundsException (the list is yet empty)

when(spy.get(0)).thenReturn("foo");

//You have to use doReturn() for stubbing

doReturn("foo").when(spy).get(0);

因為用when(spy.f1())會導緻f1()方法被真正執行,是以就需要另一種寫法。

http://blog.csdn.net/dc_726/article/details/8568537

Use <code>doCallRealMethod()</code> when you want to call the real implementation of a method.

As usual you are going to read the partial mock warning: Object oriented programming is more less tackling complexity by dividing the complexity into separate, specific, SRPy objects. How does partial mock fit into this paradigm? Well, it just doesn't... Partial mock usually means that the complexity has been moved to a different method on the same object. In most cases, this is not the way you want to design your application.

However, there are rare cases when partial mocks come handy: dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.) However, I wouldn't use partial mocks for new, test-driven &amp; well-designed code.

Example:

<dl></dl>

<dt>Returns:</dt>

<dd>stubber - to select a method for stubbing</dd>

  通過代碼可以看出Jerry是一個mock對象, goHome()和doSomeThingB()是使用了實際調用技術,而doSomeThingA()被mockito執行了預設的answer行為(這裡是個void方法,so,什麼也不幹)。

總結:

    spy和callrealmethod都可以實作部分mock,唯一不同的是通過spy做的樁實作仍然會調用實際方法(我都懷疑這是不是作者的bug)。

    批注:spy方法需要使用doReturn方法才不會調用實際方法。

    mock技術是實施TDD過程必備的裝備,熟練掌握mockito(或者其他工具)可以更有效的進行測試。雖然mockito作者也覺得部分測試不是好的設計,但是在java這樣一個不是完全面向對象技術的平台上,我們其實沒必要過分糾結這些細節,簡潔,可靠的代碼才是我們需要的。

http://heipark.iteye.com/blog/1496603