(注:このブログはもう更新していません)この日記は私的なものであり所属会社の見解とは無関係です。 GitHub: takahashikzn

[クラウド帳票エンジンDocurain]

Mockito1.8.5リファレンス 日本語訳(途中)

2010-10-19追記

既に翻訳に着手されている方がいるようです。(1.8.1版がベース)
http://tech.cm55.com/wiki/mockito/Manual
こちらもあわせてお読みください。


職場の同僚ケンタロウ氏よりタレコミ頂きました。どうもありがとうございます。

本文ここから

Mockitoの日本語訳が存在しないようなので、途中まで訳してみました。
原文はこちら


僕の英語力では良くわからなかった所は、コソッと誤魔化してます(笑)
「ここは、こう訳した方がいいよ!」などあれば、ご指摘お待ちしております。





Mockito library enables mocks creation, verification and stubbing.
This javadoc content is also available on the http://mockito.org web page.
All documentation is kept in javadocs because it guarantees consistency between what's on the web and what's in the source code.
Also, it makes possible to access documentation straight from the IDE even if you work offline.

Mockitoはモックの作成・検証・スタブ化を可能にするライブラリです。
このJavadochttp://mockito.orgでも参照できます。
全てのドキュメントはJavadocとして管理しています。それはドキュメントと実装の乖離を防ぎたいからです。
また、IDEでドキュメントを読むのにも便利だから、というのも理由の一つです。

Contents

目次

1. Let's verify some behaviour!
振る舞いを検証しよう!


2. How about some stubbing?
スタブ化ってどんな感じ?


3. Argument matchers
引数マッチャー


4. Verifying exact number of invocations / at least once / never
メソッド呼び出しの回数を検証する。(少なくとも1回、とか一度も呼ばれない、等)


5. Stubbing void methods with exceptions
voidを返すメソッドが例外を投げるようにするには


6. Verification in order
メソッド呼び出しの順番を検証する


7. Making sure interaction(s) never happened on mock
モックに対して「何もしない」ということを検証する


8. Finding redundant invocations
不要なメソッド呼び出しを検知する


9. Shorthand for mocks creation - @Mock annotation
モック作成をラクに行う(@Mockアノテーションの使い方)


10. Stubbing consecutive calls (iterator-style stubbing)
メソッドの連続呼び出しにおけるスタブ化


11. Stubbing with callbacks
コールバックを利用したスタブ


12. doThrow()|doAnswer()|doNothing()|doReturn() family of methods mostly for stubbing voids
voidを返すメソッドのためのdoXXX()系メソッドについて


13. Spying on real objects
リアルなオブジェクトの振る舞いを変えるためのspyメソッド


14. Changing default return values of unstubbed invocations (Since 1.7)
モックのデフォルト動作を変更する


15. Capturing arguments for further assertions (Since 1.8.0)
引数の検証


16. Real partial mocks (Since 1.8.0)
部分モックについて


17. Resetting mocks (Since 1.8.0)
モックのリセット


18. Troubleshooting & validating framework usage (Since 1.8.0)
Mockitoの正しい使い方とトラブルシューティング


19. Aliases for behavior driven development (Since 1.8.0)
振る舞いドリブン開発のためのエイリアスメソッド


20. Serializable mocks (Since 1.8.1)
直列化可能なモック


21. New annotations: @Captor, @Spy, @InjectMocks (Since 1.8.3)
新しいあのアノテーション(@Capture, @Spy, @InjectMocks)


22. (**New**) Verification with timeout (Since 1.8.5)
タイムアウトの検証



Following examples mock a List, because everyone knows its interface (methods like add(), get(), clear() will be used).
You probably wouldn't mock List class 'in real'.


以下、皆様おなじみのjava.util.Listを題材に取り、add, get, clearなどをモックの例として採用しています。
(多分、本当にListをモック化することはないと思いますけどね)

1. Let's verify some behaviour!

振る舞いを検証しよう!

//Let's import Mockito statically so that the code looks clearer
//コードを簡潔にするためにMockitoをスタティックインポートする
import static org.mockito.Mockito.*;

//mock creation
//モックの作成
List mockedList = mock(List.class);

//using mock object
//モックを使う
mockedList.add("one");
mockedList.clear();

//verification
//検証する
verify(mockedList).add("one");
verify(mockedList).clear();

Once created, mock will remember all interactions. Then you can selectively verify whatever interaction you are interested in.
モックは、すべてのインタラクション(=メソッド呼び出し)を記憶しています。だから自分が検証したいメソッド呼び出しだけを検証できます。

2. How about some stubbing?

スタブ化ってどんな感じ?

//You can mock concrete classes, not only interfaces
//インタフェースだけでなく、具象クラスもモック化できます
LinkedList mockedList = mock(LinkedList.class);

//stubbing
//スタブ化
when(mockedList.get(0)).thenReturn("first");
when(mockedList.get(1)).thenThrow(new RuntimeException());

//following prints "first"
//文字列"first"を出力する
System.out.println(mockedList.get(0));

//following throws runtime exception
//ランタイム例外をスローする
System.out.println(mockedList.get(1));

//following prints "null" because get(999) was not stubbed
//「mockedList.get(999)」はスタブ化されていないので、"null"を出力する。(デフォルトの動作)
System.out.println(mockedList.get(999));
 
//Although it is possible to verify a stubbed invocation, usually it's just redundant
//If your code cares what get(0) returns then something else breaks (often before even verify() gets executed).
//If your code doesn't care what get(0) returns then it should not be stubbed. Not convinced? See here.
//スタブ化されたメソッド呼び出しを検証することはもちろん可能だが、たいていそれは無駄な行為である。
//もし貴方が書いたコードがget(0)の戻り値を使っているのなら、動作結果は明らかだからである。
//もし貴方が書いたコードがget(0)の戻り値を使わないのなら、スタブ化するべきではない。
//ここの議論がよくわからない?では http://monkeyisland.pl/2008/04/26/asking-and-telling を読め。
verify(mockedList).get(0);


By default, for all methods that return value, mock returns null, an empty collection or appropriate primitive/primitive wrapper value
(e.g: 0, false, ... for int/Integer, boolean/Boolean, ...).
Stubbing can be overridden: for example common stubbing can go to fixture setup but the test methods can override it.
Please note that overridding stubbing is a potential code smell that points out too much stubbing
Once stubbed, the method will always return stubbed value regardless of how many times it is called.
Last stubbing is more important - when you stubbed the same method with the same arguments many times.


デフォルトでは、全てのモック呼出はnullや、空のCollectionや、適切なプリミティブ型の値(0, false,等)を返すようになっています。
但しその動作は、スタブ化により変更可能です。
注意しなければならないのは、過度なスタブ化はコードの品質を損ねるということです。
一度スタブ化されたメソッドは、何度呼び出されようがスタブ値を返すようになります。
何度も同一メソッドをスタブ化しようとも、最後に指示したスタブ化だけが有効になります。

3. Argument matchers

引数マッチャー


Mockito verifies argument values in natural java style: by using an equals() method. Sometimes,
when extra flexibility is required then you might use argument matchers:


Mockitoは引数の値を、自然なJavaプログラムの書き方をするだけで検証できます。
検証にはequalsメソッドが使われますが、引数マッチャーを使うことで、より高度は検証を行うこともできます。

//stubbing using built-in anyInt() argument matcher
//anyInt()メソッドを使って引数マッチングをスタブ化する
when(mockedList.get(anyInt())).thenReturn("element");

//stubbing using hamcrest (let's say isValid() returns your own hamcrest matcher):
//hamcrestを使ったスタブ化(isValidは貴方の書いたhamcrestマッチャーを返す)
when(mockedList.contains(argThat(isValid()))).thenReturn("element");

//following prints "element"
//"element"を出力する
System.out.println(mockedList.get(999));

//you can also verify using an argument matcher
//検証において引数マッチャーを使うことも可能
verify(mockedList).get(anyInt());


Argument matchers allow flexible verification or stubbing.
Click here to see more built-in matchers and examples of custom argument matchers / hamcrest matchers.


引数マッチャーにより、高度な検証やスタブ化を行うことが可能です。
詳しくは http://docs.mockito.googlecode.com/hg/org/mockito/Matchers.html を参照してください。



For information solely on custom argument matchers check out javadoc for ArgumentMatcher class.


ArgumentMatcherについてはjavadocを参照してください。


Be reasonable with using complicated argument matching.
The natural matching style using equals() with occasional anyX() matchers tend to give clean & simple tests.
Sometimes it's just better to refactor the code to allow equals() matching or even implement equals() method to help out with testing.


引数マッチャーを使うべき場所は慎重に検討してください。
equalsを使ったデフォルトのマッチャーや、anyX()をつかったマッチャーだけを使うように心がけるとテストをシンプルに書けると思います。
場合によってはequalsを使ったマッチャーを使うようリファクタリングしてしまうとか、テストをシンプルにするためにequalsを実装するのもアリでしょう。



Also, read section 15 or javadoc for ArgumentCaptor class.
ArgumentCaptor is a special implementation of an argument matcher that captures argument values for further assertions.


引数を検証するために、ArgumentCaptorという特別な引数マッチングクラスがあります。
詳しくは15章やjavadocを参照してください。



Warning on argument matchers:


引数マッチャーの注意点



If you are using argument matchers, all arguments have to be provided by matchers.


引数マッチャーを使う場合、すべての引数で引数マッチャーを使う必要があります。



E.g: (example shows verification but the same applies to stubbing):


以下の例は、スタブ化でも同じことが当てはまります。

  verify(mock).someMethod(anyInt(), anyString(), eq("third argument"));
  //above is correct - eq() is also an argument matcher
  //これは正しい。eq()は引数マッチャーだから
  
  verify(mock).someMethod(anyInt(), anyString(), "third argument");
  //above is incorrect - exception will be thrown because third argument is given without an argument matcher.
  //これは正しくない。例外がスローされる。第3引数は引数マッチャーを使っていないため

4. Verifying exact number of invocations / at least x / never

メソッド呼び出しの回数を検証する。(少なくとも1回、とか一度も呼ばれない、等)

//using mock 
//モックを使う
mockedList.add("once");

mockedList.add("twice");
mockedList.add("twice");

mockedList.add("three times");
mockedList.add("three times");
mockedList.add("three times");

//following two verifications work exactly the same - times(1) is used by default
//以下の2つの検証は全く同一の意味である
verify(mockedList).add("once");
verify(mockedList, times(1)).add("once");

//exact number of invocations verification
//何回呼ばれたかを検証する
verify(mockedList, times(2)).add("twice");
verify(mockedList, times(3)).add("three times");

//verification using never(). never() is an alias to times(0)
//never()を使った検証。never()はtimes(0)と同じ意味
verify(mockedList, never()).add("never happened");

//verification using atLeast()/atMost()
//atLeastやatMostを使った検証
verify(mockedList, atLeastOnce()).add("three times");
verify(mockedList, atLeast(2)).add("five times");
verify(mockedList, atMost(5)).add("three times");

times(1) is the default. Therefore using times(1) explicitly can be omitted.


デフォルトではtimes(1)が指定されています。だからtimes(1)とわざわざ書く必要はありません。


5. Stubbing void methods with exceptions

voidを返すメソッドが例外を投げるようにするには

  doThrow(new RuntimeException()).when(mockedList).clear();
  
  //following throws RuntimeException:
  //これはRuntimeExceptionをスローする
  mockedList.clear();


Read more about doThrow|doAnswer family of methods in paragraph 12.
Initially, stubVoid(Object) was used for stubbing voids.
Currently stubVoid() is deprecated in favor of doThrow(Throwable).
This is because of improved readability and consistency with the family of doAnswer(Answer) methods.


より詳しくは12章を参照してください。
昔は、voidを返すメソッドのためにstubVoid(Object)が用意されていましたが、現在では非推奨です。
可読性向上のためにも、doXXX()系を使うようにしてください。


6. Verification in order

メソッド呼び出しの順番を検証する

List firstMock = mock(List.class);
List secondMock = mock(List.class);

//using mocks
//モックを使う
firstMock.add("was called first");
secondMock.add("was called second");

//create inOrder object passing any mocks that need to be verified in order
//呼び出し順序を検証するために、モックオブジェクトを渡してinOrderを作成する
InOrder inOrder = inOrder(firstMock, secondMock);

//following will make sure that firstMock was called before secondMock
//firstMockがsecondMockの前に呼ばれたことを検証する
inOrder.verify(firstMock).add("was called first");
inOrder.verify(secondMock).add("was called second");


Verification in order is flexible - you don't have to verify all interactions one-by-one
but only those that you are interested in testing in order.
Also, you can create InOrder object passing only mocks that are relevant for in-order verification.


呼び出し順序の検証をやりすぎると、(テストコードが)不安定になります。
例えば全てのメソッド呼び出しについて順序を検証したりするのはやめましょう。
テストしたい箇所についてのみ順序の検証を行うべきです。
なお、モックオブジェクトひとつだけのでの呼び出し順序の検証も可能です。

7. Making sure interaction(s) never happened on mock

モックに対して「何もしない」ということを検証する

//using mocks - only mockOne is interacted
//mockOneだけ使用する
mockOne.add("one");

//ordinary verification
//フツーの検証
verify(mockOne).add("one");

//verify that method was never called on a mock
//メソッドが呼ばれてないことの検証
verify(mockOne, never()).add("two");

//verify that other mocks were not interacted
//mockTwoとmockThreeについては何も行われていないことを検証
verifyZeroInteractions(mockTwo, mockThree);

8. Finding redundant invocations

不要なメソッド呼び出しを検知する

//using mocks
//モックを使う
mockedList.add("one");
mockedList.add("two");

verify(mockedList).add("one");

//following verification will fail 
//この検証は失敗する
verifyNoMoreInteractions(mockedList);

A word of warning: Some users who did a lot of classic,
expect-run-verify mocking tend to use verifyNoMoreInteractions() very often, even in every test method.
verifyNoMoreInteractions() is not recommended to use in every test method.
verifyNoMoreInteractions() is a handy assertion from the interaction testing toolkit.
Use it only when it's relevant. Abusing it leads to overspecified, less maintainable tests. You can find further reading here.
See also never() - it is more explicit and communicates the intent well.


「スタブ化→テスト実行→検証」という古典的フローになれた方はverifyNoMoreInteractionsを使いたがります。いつも。
でも、verifyNoMoreInteractionsをいつも使うのは推奨しません。
verifyNoMoreInteractionsは"the interaction testing toolkit"(訳注:要するにEasyMockのこと)から輸入してきたものです。
必要なときのみ使用するようにしてください。濫用すると、テストコードのメンテナンス性が下がります。
この議論について詳しく読みたいなら http://monkeyisland.pl/2008/07/12/should-i-worry-about-the-unexpected/ を参照してください。


9. Shorthand for mocks creation - @Mock annotation

モック作成をラクに行う(@Mockアノテーションの使い方)


Minimizes repetitive mock creation code.
Makes the test class more readable.
Makes the verification error easier to read because the field name is used to identify the mock.


モック作成をよりシンプルになります。
テストクラスをより読みやすくします。
フィールド名がモックの特定に使用されるため、検証エラーを判別しやすくなります。

  public class ArticleManagerTest { 
    
      @Mock private ArticleCalculator calculator;
      @Mock private ArticleDatabase database;
      @Mock private UserProvider userProvider;
    
      private ArticleManager manager;

Important! This needs to be somewhere in the base class or a test runner:


注意!これを使うならば親クラスやテストランナーなどで以下のコードを実行する必要があります。

MockitoAnnotations.initMocks(testClass);

You can use built-in runner: MockitoJUnitRunner.
Read more here: MockitoAnnotations

MockitoJUnitRunnerを使うのもアリです。

10. Stubbing consecutive calls (iterator-style stubbing)

メソッドの連続呼び出しをスタブ化する(イテレータのスタブ化)


Sometimes we need to stub with different return value/exception for the same method call.
Typical use case could be mocking iterators.
Original version of Mockito did not have this feature to promote simple mocking.
For example, instead of iterators one could use Iterable or simply collections.
Those offer natural ways of stubbing (e.g. using real collections).
In rare scenarios stubbing consecutive calls could be useful, though:


たまに、毎回違う値を返すスタブ化が必要になるかもしれません。
典型的な例は、イテレータのモックを作成する場合です。
最初のバージョンのMockitoはそのような機能を提供していませんでした。
例えば、イテレータを使う代わりにIterableやCollectionを使うことができました。
これはスタブ化を行うための一番自然なスタイルです。
(要するに実際のコレクションクラスをそのまま使えということです)


だけど極稀に、メソッドの連続呼び出しをスタブ化する方が良いかもしれません。例えば以下のように。

when(mock.someMethod("some arg"))
  .thenThrow(new RuntimeException())
  .thenReturn("foo");

//First call: throws runtime exception:
//最初の呼び出し:ランタイム例外をスロー
mock.someMethod("some arg");

//Second call: prints "foo"
//二度目の呼び出し:"foo"を出力する
System.out.println(mock.someMethod("some arg"));

//Any consecutive call: prints "foo" as well (last stubbing wins). 
//それ以上の呼出は、最後のスタブ化が有効
System.out.println(mock.someMethod("some arg"));


Alternative, shorter version of consecutive stubbing:


メソッドの連続呼び出しにおけるスタブ化を、以下のように簡潔に書く事ができます

when(mock.someMethod("some arg"))
  .thenReturn("one", "two", "three");

11. Stubbing with callbacks

コールバックを利用したスタブ


Allows stubbing with generic Answer interface.
Yet another controversial feature which was not included in Mockito originally.
We recommend using simple stubbing with thenReturn() or thenThrow() only.
Those two should be just enough to test/test-drive any clean & simple code.


このような、議論を醸しそうな機能はかつてのMockitoにはなかったのですが、
汎用的なAnswerインタフェースを使ったスタブ化が可能です。


ただし我々は、thenReturnとかthenThrowなどのシンプルなスタブ化だけを使うことを推奨します。
この2つだけでも、簡潔なテストコードを記述するのには充分なはずです。

when(mock.someMethod(anyString())).thenAnswer(new Answer() {
    Object answer(InvocationOnMock invocation) {
        Object[] args = invocation.getArguments();
        Object mock = invocation.getMock();
        return "called with arguments: " + args;
    }
});

//Following prints "called with arguments: foo"
//"called with arguments: foo"を出力する
System.out.println(mock.someMethod("foo"));

12. doThrow()|doAnswer()|doNothing()|doReturn() family of methods for stubbing voids (mostly)

voidを返すメソッドのためのdoXXX()系メソッドについて


Stubbing voids requires different approach from when(Object)
because the compiler does not like void methods inside brackets...
doThrow(Throwable) replaces the stubVoid(Object) method for stubbing voids.
The main reason is improved readability and consistency with the family of doAnswer() methods.


voidを返すメソッドのスタブ化は、when(Object)とは異なるアプローチが必要です。
なぜなら、voidを返すメソッドの呼出ををカッコの中に書くとコンパイルエラーになるからです。


主に可読性の観点から、doXXX()系を用意しています。stubVoid(Object)を使うのはオススメしません。


Use doThrow() when you want to stub a void method with an exception:


voidを返すメソッドが例外を返すようにスタブ化するにあたり、doThrowを使います。

  doThrow(new RuntimeException()).when(mockedList).clear();
  
  //following throws RuntimeException:
  //RuntimeExceptionをスローする
  mockedList.clear();

Read more about other methods:


詳しくは各々のJavadocを参照してください。



doThrow(Throwable)
doAnswer(Answer)
doNothing()
doReturn(Object)


13. Spying on real objects

実際のクラスの振る舞いを変えるためのspyメソッド


You can create spies of real objects.
When you use the spy then the real methods are called (unless a method was stubbed).
Real spies should be used carefully and occasionally, for example when dealing with legacy code.


リアルな(訳注:モックではないクラスの)オブジェクトの動作を部分的に差し替えるために、spyメソッドが使えます。(メソッドのスタブ化は不要です)
例えばレガシーコードを扱う場合、spyメソッドは注意深く・適切に使用しなければなりません。



Spying on real objects can be associated with "partial mocking" concept.
Before the release 1.8, Mockito spies were not real partial mocks.
The reason was we thought partial mock is a code smell.
At some point we found legitimate use cases for partial mocks
(3rd party interfaces, interim refactoring of legacy code, the full article is here)


リアルなオブジェクトをspy化することで、部分的にモック化することができます。
Mockitoリリース1.8以前では、部分モックはできませんでした。
なぜなら我々は、部分モックはコード品質に悪影響を及ぼすと考えていたからです。
ただしいくつかのケースにおいて、部分モックが有効であることがわかりました。
(サードパーティ製品のインタフェースや、レガシーコードの暫定的なリファクタリング中とか。
詳しくは http://monkeyisland.pl/2009/01/13/subclass-and-override-vs-partial-mocking-vs-refactoring を参照してください)

  List list = new LinkedList();
  List spy = spy(list);

  //optionally, you can stub out some methods:
  //メソッドを選択的にスタブ化できる
  when(spy.size()).thenReturn(100);

  //using the spy calls real methods
  spy.add("one");
  spy.add("two");

  //prints "one" - the first element of a list
  //リストの最初の要素である"one"を表示する。
  System.out.println(spy.get(0));

  //size() method was stubbed - 100 is printed
  //size()メソッドはスタブ化されているので100が表示される
  System.out.println(spy.size());

  //optionally, you can verify
  //検証することも可能
  verify(spy).add("one");
  verify(spy).add("two");

Important gotcha on spying real objects!


リアルなオブジェクトのスパイ化についてはいくつかのお約束事項が存在します。



1. Sometimes it's impossible to use when(Object) for stubbing spies. Example:


いくつかのケースに置いて、when(Object)が使えません。以下の例を参照。

		   List list = new LinkedList();
		   List spy = spy(list);
		   
		   //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
		   //これはダメ。スタブ化されていないリアルなメソッドが呼ばれるので、IndexOutOfBoundsExceptionがスローされてしまう
		   //(リストは依然として空だから)
		   when(spy.get(0)).thenReturn("foo");
		   
		   //You have to use doReturn() for stubbing
		   //doReturnを使ってスタブ化する必要がある
		   doReturn("foo").when(spy).get(0);

2. Watch out for final methods. Mockito doesn't mock final methods so the bottom line is:
when you spy on real objects + you try to stub a final method = trouble.
What will happen is the real method will be called *on mock* but *not on the real instance* you passed to the spy() method.
Typically you may get a NullPointerException because mock instances don't have fields initiated.


finalメソッドはスタブ化してはいけません。トラブルの元になります。
もしスタブ化すると、「リアルなメソッドがモックオブジェクト上のメソッドとして呼ばれます」
たいていこれは、ヌルポなどを引き起こすことになるでしょう。




===========================================
以降はまだ訳してません
===========================================







14. Changing default return values of unstubbed invocations (Since 1.7)

You can create a mock with specified strategy for its return values. It's quite advanced feature and typically you don't need it to write decent tests. However, it can be helpful for working with legacy systems.
It is the default answer so it will be used only when you don't stub the method call.

Foo mock = mock(Foo.class, Mockito.RETURNS_SMART_NULLS);
Foo mockTwo = mock(Foo.class, new YourOwnAnswer());

Read more about this interesting implementation of Answer: RETURNS_SMART_NULLS



15. Capturing arguments for further assertions (Since 1.8.0)

Mockito verifies argument values in natural java style: by using an equals() method. This is also the recommended way of matching arguments because it makes tests clean & simple. In some situations though, it is helpful to assert on certain arguments after the actual verification. For example:
ArgumentCaptor argument = ArgumentCaptor.forClass(Person.class);
verify(mock).doSomething(argument.capture());
assertEquals("John", argument.getValue().getName());

Warning: it is recommended to use ArgumentCaptor with verification but not with stubbing. Using ArgumentCaptor with stubbing may decrease test readability because captor is created outside of assert (aka verify or 'then') block. Also it may reduce defect localization because if stubbed method was not called then no argument is captured.
In a way ArgumentCaptor is related to custom argument matchers (see javadoc for ArgumentMatcher class). Both techniques can be used for making sure certain arguments where passed to mocks. However, ArgumentCaptor may be a better fit if:

custom argument matcher is not likely to be reused
you just need it to assert on argument values to complete verification
Custom argument matchers via ArgumentMatcher are usually better for stubbing.
16. Real partial mocks (Since 1.8.0)

Finally, after many internal debates & discussions on the mailing list, partial mock support was added to Mockito. Previously we considered partial mocks as code smells. However, we found a legitimate use case for partial mocks - more reading: here
Before release 1.8 spy() was not producing real partial mocks and it was confusing for some users. Read more about spying: here or in javadoc for spy(Object) method.

//you can create partial mock with spy() method:
List list = spy(new LinkedList());

//you can enable partial mock capabilities selectively on mocks:
Foo mock = mock(Foo.class);
//Be sure the real implementation is 'safe'.
//If real implementation throws exceptions or depends on specific state of the object then you're in trouble.
when(mock.someMethod()).thenCallRealMethod();

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 & well-designed code.

17. Resetting mocks (Since 1.8.0)

Smart Mockito users hardly use this feature because they know it could be a sign of poor tests. Normally, you don't need to reset your mocks, just create new mocks for each test method.
Instead of reset() please consider writing simple, small and focused test methods over lengthy, over-specified tests. First potential code smell is reset() in the middle of the test method. This probably means you're testing too much. Follow the whisper of your test methods: "Please keep us small & focused on single behavior". There are several threads about it on mockito mailing list.

The only reason we added reset() method is to make it possible to work with container-injected mocks. See issue 55 (here) or FAQ (here).

Don't harm yourself. reset() in the middle of the test method is a code smell (you're probably testing too much).

List mock = mock(List.class);
when(mock.size()).thenReturn(10);
mock.add(1);

reset(mock);
//at this point the mock forgot any interactions & stubbing

18. Troubleshooting & validating framework usage (Since 1.8.0)

First of all, in case of any trouble, I encourage you to read the Mockito FAQ: http://code.google.com/p/mockito/wiki/FAQ
In case of questions you may also post to mockito mailing list: http://groups.google.com/group/mockito

Next, you should know that Mockito validates if you use it correctly all the time. However, there's a gotcha so please read the javadoc for validateMockitoUsage()

19. Aliases for behavior driven development (Since 1.8.0)

Behavior Driven Development style of writing tests uses //given //when //then comments as fundamental parts of your test methods. This is exactly how we write our tests and we warmly encourage you to do so!
Start learning about BDD here: http://en.wikipedia.org/wiki/Behavior_Driven_Development

The problem is that current stubbing api with canonical role of when word does not integrate nicely with //given //when //then comments. It's because stubbing belongs to given component of the test and not to the when component of the test. Hence BDDMockito class introduces an alias so that you stub method calls with BDDMockito.given(Object) method. Now it really nicely integrates with the given component of a BDD style test!

Here is how the test might look like:

import static org.mockito.BDDMockito.*;

Seller seller = mock(Seller.class);
Shop shop = new Shop(seller);

public void shouldBuyBread() throws Exception {
//given
given(seller.askForBread()).willReturn(new Bread());

//when
Goods goods = shop.buyBread();

//then
assertThat(goods, containBread());
}

20. (**New**) Serializable mocks (Since 1.8.1)

Mocks can be made serializable. With this feature you can use a mock in a place that requires dependencies to be serializable.
WARNING: This should be rarely used in unit testing.

The behaviour was implemented for a specific use case of a BDD spec that had an unreliable external dependency. This was in a web environment and the objects from the external dependency were being serialized to pass between layers.

To create serializable mock use MockSettings.serializable():

List serializableMock = mock(List.class, withSettings().serializable());

The mock can be serialized assuming all the normal serialization requirements are met by the class.

Making a real object spy serializable is a bit more effort as the spy(...) method does not have an overloaded version which accepts MockSettings. No worries, you will hardly ever use it.

List list = new ArrayList();
List spy = mock(ArrayList.class, withSettings()
.spiedInstance(list)
.defaultAnswer(CALLS_REAL_METHODS)
.serializable());

21. (**New**) New annotations: @Captor, @Spy, @InjectMocks (Since 1.8.3)

Release 1.8.3 brings new annotations that may be helpful on occasion:

@Captor simplifies creation of ArgumentCaptor - useful when the argument to capture is a nasty generic class and you want to avoid compiler warnings
@Spy - you can use it instead spy(Object).
@InjectMocks - injects mocks into tested object automatically.
All new annotations are *only* processed on MockitoAnnotations.initMocks(Object)

22. (**New**) Verification with timeout (Since 1.8.5)

Allows verifying with timeout. May be useful for testing in concurrent conditions.

It feels this feature should be used rarely - figure out a better way of testing your multi-threaded system.

Not yet implemented to work with InOrder verification.

Examples:

//passes when someMethod() is called within given time span
verify(mock, timeout(100)).someMethod();
//above is an alias to:
verify(mock, timeout(100).times(1)).someMethod();

//passes when someMethod() is called *exactly* 2 times within given time span
verify(mock, timeout(100).times(2)).someMethod();

//passes when someMethod() is called *at lest* 2 times within given time span
verify(mock, timeout(100).atLeast(2)).someMethod();

//verifies someMethod() within given time span using given verification mode
//useful only if you have your own custom verification modes.
verify(mock, new Timeout(100, yourOwnVerificationMode)).someMethod();