JMockit An automated testing toolkit for Java

Mocking

  1. Mocked types and instances
    モック型とインスタンス
  2. Expectations
    期待
  3. The record-replay-verify model
    記録・再生・検証モデル
  4. Instantiation and injection of tested classes
    テスト対象のクラスのインスタンス化と注入
  5. Recording results for an expectation
    期待の結果を記録する
  6. Flexible matching of argument values
    引数値の柔軟なマッチング
    1. Using the "any" fields
      「任意」フィールドの使用
    2. Using the "with" methods
      「with」メソッドの使用
  7. Specifying invocation count constraints
    呼び出し回数の制約を指定する
  8. Explicit verification
    明示的な検証
    1. Verification in order
      順番に検証
    2. Full verification
      完全な検証
  9. Delegates: specifying custom results
    デリゲート: カスタム結果の指定
  1. Capturing invocation arguments for verification
    検証のための呼び出し引数のキャプチャ
    1. Capturing arguments from a single invocation
      単一の呼び出しから引数を取得する
    2. Capturing arguments from multiple invocations
      複数の呼び出しから引数を取得する
    3. Capturing new instances
      新しいインスタンスのキャプチャ
  2. Cascading mocks
    カスケードモック
    1. Cascading static factory methods
      静的ファクトリーメソッドのカスケード
    2. Cascading self-returning methods
      カスケード自己復帰メソッド
  3. Matching invocations to specific instances
    特定のインスタンスへの呼び出しのマッチング
    1. Injectable mocked instances
      注入可能なモックインスタンス
    2. Declaring multiple mocked instances
      複数のモックインスタンスを宣言する
    3. Instances created with a given constructor
      指定されたコンストラクタで作成されたインスタンス
  4. Partial mocking
    部分的な嘲笑
  5. Mocking unspecified implementation classes
    未指定の実装クラスのモック

In the JMockit library, the Expectations API provides rich support for the use of mocking in automated developer tests.
JMockit ライブラリでは、Expectations API が自動化された開発者テストでのモックの使用を豊富にサポートします。
When mocking is used, a test focuses on the behavior of the code under test, as expressed through its interactions with other types it depends upon.
モックを使用すると、テストは、テスト対象のコードが依存する他の型との相互作用を通じて表現される、テスト対象のコードの動作に重点を置きます。
Mocking is typically used in the construction of isolated unit tests, where a unit under test is exercised in isolation from the implementation of other units it depends on.
モックは通常、テスト対象のユニットが、それが依存する他のユニットの実装から分離して実行される、分離されたユニット テストの構築に使用されます。
Typically, a unit of behavior is a single class, but it's also fine to consider a whole set of strongly-related classes as a single unit for the purposes of unit testing (as is usually the case when we have a central public class with one or more helper classes, possibly package-private); in general, individual methods should not be regarded as separate units on their own.
通常、動作の単位は単一のクラスですが、ユニット テストの目的で、密接に関連するクラスのセット全体を単一の単位と見なすことも問題ありません (通常は、中心となるパブリック クラスと、おそらくパッケージ プライベートの 1 つ以上のヘルパー クラスがある場合に該当します)。一般に、個々のメソッドは、それ自体を個別の単位と見なすべきではありません。

Strict unit testing, however, is not a recommended approach; one should not attempt to mock every single dependency.
ただし、厳密な単体テストは推奨されるアプローチではありません。すべての依存関係をモック化しようとすべきではありません。
Mocking is best used in moderation; whenever possible, favor integration tests over isolated unit tests.
モックは適度に使用するのが最適です。可能な場合は、分離された単体テストよりも統合テストを優先してください。
This said, mocking is occasionally also useful in the creation of integration tests, when some particular dependency cannot have its real implementation easily used, or when attempting to create tests for corner cases where a well-placed mocked interaction can greatly facilitate the test.
そうは言っても、特定の依存関係の実際の実装を簡単に使用できない場合や、適切に配置されたモック化された相互作用によってテストが大幅に容易になるコーナーケースのテストを作成しようとする場合など、統合テストの作成にもモックが役立つことがあります。

1 Mocked types and instances

Mocking provides a mechanism for isolating a class to be tested from (some of) its dependencies.
モックは、テスト対象のクラスをその依存関係の一部から分離するメカニズムを提供します。
We specify which particular dependencies are to be mocked by declaring suitable mock fields and/or mock parameters in a test class; mock fields are declared as annotated instance fields of the test class, while mock parameters are declared as annotated parameters of a test method.
テスト クラスで適切なモック フィールドやモック パラメータを宣言することで、どの特定の依存関係をモックするかを指定します。モック フィールドはテスト クラスの注釈付きインスタンス フィールドとして宣言され、モック パラメータはテスト メソッドの注釈付きパラメータとして宣言されます。
The type of the mock field or parameter can be any kind of reference type: an interface, a class (including abstract and final ones), an annotation, or an enum.
モック フィールドまたはパラメーターの型は、インターフェイス、クラス (抽象クラスと最終クラスを含む)、アノテーション、列挙型など、任意の種類の参照型にすることができます。

The following example test skeleton (using Java 8 and JUnit 5) serves as a basic illustration for the declaration of mock fields and mock parameters, as well as the way in which they are typically used in test code.
次のサンプル テスト スケルトン (Java 8 および JUnit 5 を使用) は、モック フィールドとモック パラメーターの宣言、およびそれらがテスト コードで一般的に使用される方法の基本的な例となります。

@Mocked Dependency mockInstance; // holds a mocked instance automatically created for use in each test
各テストで使用するために自動的に作成されたモックインスタンスを保持します
@Test void doBusinessOperationXyz(@Mocked AnotherDependency anotherMock) { ... new Expectations() {{ // an "expectation block" ... // Record an expectation, with a given value to be returned:
返される特定の値を含む期待値を記録します。
mockInstance.mockedMethod(...); result = 123; ... }}; ... // Call the code under test.
テスト対象のコードを呼び出します。
... new Verifications() {{ // a "verification block" // Verifies an expected invocation:
予想される呼び出しを検証します。
anotherMock.save(any); times = 1; }}; ... }

For a mock parameter declared in a test method, an instance of the declared type will be automatically created by JMockit and passed by the JUnit/TestNG test runner when it executes the test method; therefore, the parameter value will never be null.
テスト メソッドで宣言されたモック パラメーターの場合、宣言された型のインスタンスが JMockit によって自動的に作成され、テスト メソッドの実行時に JUnit/TestNG テスト ランナーによって渡されます。したがって、パラメーター値が null になることはありません。
For a mock field, an instance of the declared type will be automatically created and assigned to the field (provided it's not final).
モック フィールドの場合、宣言された型のインスタンスが自動的に作成され、フィールドに割り当てられます (final でない場合)。

There are three different mocking annotations we can use when declaring mock fields and parameters:
モック フィールドとパラメーターを宣言するときに使用できる 3 つの異なるモック注釈があります。
@Mocked, which will mock all methods and constructors on all existing and future instances of a mocked class (for the duration of the tests using it); @Injectable, which constrains mocking to the instance methods of a single mocked instance; and @Capturing, which extends mocking to the classes implementing a mocked interface, or the subclasses extending a mocked class.
@Mocked は、モックされたクラスの既存および将来のすべてのインスタンスのすべてのメソッドとコンストラクターをモックします (これを使用するテストの期間中)。@Injectable は、モックを単一のモックされたインスタンスのインスタンス メソッドに制限します。@Capturing は、モックされたインターフェースを実装するクラス、またはモックされたクラスを拡張するサブクラスにモックを拡張します。

The mocked instances created by JMockit can be used normally in test code (for the recording and verification of expectations), and/or passed to the code under test.
JMockit によって作成されたモックインスタンスは、通常、テスト コードで使用したり (期待値の記録と検証のため)、テスト対象のコードに渡したりできます。
Or they may simply go unused.
あるいは、単に使われないままになる可能性もあります。
Differently from other mocking APIs, these mocked objects don't have to be the ones used by the code under test when it calls instance methods on its dependencies.
他のモック API とは異なり、これらのモック オブジェクトは、テスト対象のコードが依存関係のインスタンス メソッドを呼び出すときに使用されるオブジェクトである必要はありません。
When using @Mocked or @Capturing (but not when using @Injectable), JMockit does not care on which particular object a mocked instance method is called.
@Mocked または @Capturing を使用する場合 (@Injectable を使用する場合は除く)、JMockit は、モックされたインスタンス メソッドがどの特定のオブジェクトで呼び出されるかには関心がありません。
This allows the transparent mocking of instances created directly inside code under test, when said code invokes constructors on brand new instances using the new operator; the classes instantiated must be covered by mocked types declared in test code, that's all.
これにより、テスト対象のコード内で直接作成されたインスタンスの透過的なモック化が可能になります。その場合、そのコードでは、新しいインスタンスのコンストラクターを new 演算子を使用して呼び出します。インスタンス化されたクラスは、テスト コードで宣言されたモック化された型によってカバーされる必要があります。それだけです。

2 Expectations

An expectation represents a set of invocations to a specific mocked method/constructor that is relevant for a given test.
期待値は、特定のテストに関連する特定のモック メソッド/コンストラクターへの呼び出しのセットを表します。
An expectation may cover multiple different invocations to the same method or constructor, but it doesn't have to cover all such invocations that occur during the execution of the test.
期待値は、同じメソッドまたはコンストラクターへの複数の異なる呼び出しをカバーする場合があります。ただし、テストの実行中に発生するすべての呼び出しをカバーする必要はありません。
Whether a particular invocation matches a given expectation or not will depend not only on the method/constructor signature but also on runtime aspects such as the instance on which the method is invoked, argument values, and/or the number of invocations already matched.
特定の呼び出しが特定の期待に一致するかどうかは、メソッド/コンストラクターのシグネチャだけでなく、メソッドが呼び出されるインスタンス、引数の値、および/または既に一致した呼び出しの数などの実行時の側面にも依存します。
Therefore, several types of matching constraints can (optionally) be specified for a given expectation.
したがって、特定の期待値に対して、いくつかの種類の一致制約を(オプションで)指定できます。

When we have one or more invocation parameters involved, an exact argument value may be specified for each parameter.
1 つ以上の呼び出しパラメータが関係する場合、各パラメータに対して正確な引数値を指定できます。
For example, the value "test string" could be specified for a String parameter, causing the expectation to match only those invocations with this exact value in the corresponding parameter.
たとえば、String パラメータに値「テスト文字列」を指定すると、対応するパラメータにこの正確な値を持つ呼び出しのみが期待値と一致するようになります。
As we will see later, instead of specifying exact argument values, we can specify more relaxed constraints which will match whole sets of different argument values.
後で説明するように、正確な引数値を指定する代わりに、異なる引数値のセット全体に一致する、より緩やかな制約を指定できます。

The example below shows an expectation for Dependency#someMethod(int, String), which will match an invocation to this method with the exact argument values as specified.
以下の例は、Dependency#someMethod(int, String) の期待値を示しています。これは、指定されたとおりの引数値を持つこのメソッドの呼び出しと一致します。
Notice that the expectation itself is specified through an isolated invocation to the mocked method.
期待値自体は、モック化されたメソッドへの個別の呼び出しを通じて指定されることに注意してください。
There are no special API methods involved, as is common in other mocking APIs.
他のモック API でよくあるような特別な API メソッドは使用されません。
This invocation, however, does not count as one of the "real" invocations we are interested in testing.
ただし、この呼び出しは、テスト対象の「実際の」呼び出しの 1 つとしてはカウントされません。
It's only there so that the expectation can be specified.
期待値を指定できるようにするためだけに存在します。

@Test
void doBusinessOperationXyz(@Mocked Dependency mockInstance) {
   ...
   new Expectations() {{
      ...
      // An expectation for an instance method:
インスタンス メソッドの期待値:
mockInstance.someMethod(1, "test"); result = "mocked"; ... }}; // A call to code under test occurs here, leading to mock invocations that may or may not match specified expectations.
ここでテスト対象のコードへの呼び出しが発生し、指定された期待値と一致する場合も一致しない場合もあるモック呼び出しが発生します。
}

We will see more about expectations later, after we understand the differences between recording, replaying, and verifying invocations.
呼び出しの記録、再生、検証の違いを理解した後で、期待値についてさらに詳しく説明します。

3 The record-replay-verify model

Any developer test can be divided in at least three separate execution phases.
開発者テストは、少なくとも 3 つの個別の実行フェーズに分割できます。
The phases execute sequentially, one at a time, as demonstrated below.
以下に示すように、フェーズは一度に 1 つずつ順番に実行されます。

@Test
void someTestMethod() {
   // 1. Preparation: whatever is required before the code under test can be exercised.
1. 準備: テスト対象のコードを実行する前に必要なもの。
... // 2. The code under test is exercised, usually by calling a public method.
2. テスト対象のコードは、通常はパブリック メソッドを呼び出すことによって実行されます。
... // 3. Verification: whatever needs to be checked to make sure the code exercised by the test did its job.
3. 検証: テストによって実行されたコードが機能したことを確認するためにチェックする必要があるもの。
... }

First, we have a preparation phase, where objects and data items needed for the test are created or obtained from somewhere else.
まず、準備フェーズがあり、テストに必要なオブジェクトとデータ項目が作成される、または別の場所から取得されます。
Then, code under test is exercised.
次に、テスト対象のコードが実行されます。
Finally, the results from exercising the tested code are compared with the expected results.
最後に、テストされたコードを実行した結果が予想される結果と比較されます。

This model of three phases is also known as the Arrange, Act, Assert syntax, or "AAA" for short.
この 3 つのフェーズのモデルは、Arrange、Act、Assert 構文、または略して「AAA」とも呼ばれます。
Different words, but the meaning is the same.
言葉は違いますが、意味は同じです。

In the context of behavior-based testing with mocked types (and their mocked instances), we can identify the following alternative phases, which are directly related to the three previously described conventional testing phases:
モック化された型 (およびそのモック化されたインスタンス) を使用した動作ベースのテストのコンテキストでは、前述の 3 つの従来のテスト フェーズに直接関連する次の代替フェーズを識別できます。

  1. The record phase, during which invocations can be recorded.
    呼び出しを記録できる記録フェーズ。
    This happens during test preparation, before the invocations we want to test are executed.
    これは、テストの準備中、テストする呼び出しが実行される前に発生します。
  2. The replay phase, during which the mock invocations of interest have a chance to be executed, as the code under test is exercised.
    再生フェーズでは、テスト対象のコードが実行され、目的の模擬呼び出しが実行される機会があります。
    The invocations to mocked methods/constructors previously recorded will now be replayed.
    以前に記録されたモック メソッド/コンストラクターへの呼び出しが再生されるようになりました。
    Often there isn't a one-to-one mapping between invocations recorded and replayed, though.
    ただし、記録された呼び出しと再生された呼び出しの間に 1 対 1 のマッピングが存在しないことがよくあります。
  3. The verify phase, during which invocations can be verified to have occurred as expected.
    検証フェーズでは、呼び出しが期待どおりに行われたかどうかを確認できます。
    This happens during test verification, after the invocations under test had a chance to be executed.
    これは、テスト対象の呼び出しが実行された後、テスト検証中に発生します。

Behavior-based tests written with JMockit will typically fit the following templates:
JMockit で記述された動作ベースのテストは、通常、次のテンプレートに適合します。

import mockit.*;
... other imports ...

class SomeTest {
   // Zero or more "mock fields" common to all test methods in the class:
クラス内のすべてのテスト メソッドに共通する 0 個以上の「モック フィールド」:
@Mocked Collaborator mockCollaborator; @Mocked AnotherDependency anotherDependency; ... @Test void testWithRecordAndReplayOnly(mock parameters) { // Preparation code not specific to JMockit, if any.
JMockit に固有ではない準備コード (存在する場合)。
new Expectations() {{ // an "expectation block" // One or more invocations to mocked types, causing expectations to be recorded.
モックされた型への 1 つ以上の呼び出しにより、期待値が記録されます。
// Invocations to non-mocked types are also allowed anywhere inside this block (though not recommended).
このブロック内のどこでも、モック化されていない型の呼び出しも許可されます (ただし、推奨されません)。
}}; // Code under test is exercised.
テスト対象のコードが実行されます。
// Verification code (JUnit/TestNG assertions), if any.
検証コード (JUnit/TestNG アサーション) (ある場合)。
} @Test void testWithReplayAndVerifyOnly(mock parameters) { // Preparation code not specific to JMockit, if any.
JMockit に固有ではない準備コード (存在する場合)。
// Code under test is exercised.
テスト対象のコードが実行されます。
new Verifications() {{ // a "verification block" // One or more invocations to mocked types, causing expectations to be verified.
モックされた型への 1 つ以上の呼び出しにより、期待値が検証されます。
// Invocations to non-mocked types are also allowed anywhere inside this block (though not recommended).
このブロック内のどこでも、モック化されていない型の呼び出しも許可されます (ただし、推奨されません)。
}}; // Additional verification code, if any, either here or before the verification block.
追加の検証コードがある場合は、ここまたは検証ブロックの前に入力します。
} @Test void testWithBothRecordAndVerify(mock parameters) { // Preparation code not specific to JMockit, if any.
JMockit に固有ではない準備コード (存在する場合)。
new Expectations() {{ // One or more invocations to mocked types, causing expectations to be recorded.
モックされた型への 1 つ以上の呼び出しにより、期待値が記録されます。
}}; // Code under test is exercised.
テスト対象のコードが実行されます。
new VerificationsInOrder() {{ // an ordered verification block // One or more invocations to mocked types, causing expectations to be verified in the specified order.
モックされた型への 1 つ以上の呼び出し。指定された順序で期待値が検証されます。
}}; // Additional verification code, if any, either here or before the verification block.
追加の検証コードがある場合は、ここまたは検証ブロックの前に入力します。
} }

There are other variations to the above templates, but the essence is that the expectation blocks belong to the record phase and come before the code under test is exercised, while the verification blocks belong to the verify phase.
上記のテンプレートには他にもバリエーションがありますが、本質的には、期待ブロックは記録フェーズに属し、テスト対象のコードが実行される前に配置され、検証ブロックは検証フェーズに属します。
A test method can contain any number of expectation blocks, including none. The same is true for verification blocks.
テスト メソッドには、期待ブロックをいくつでも含めることができます (期待ブロックがまったく含まれない場合もあります)。検証ブロックについても同様です。

4 Instantiation and injection of tested classes

A non-final instance field annotated as @Tested in the test class will be considered for automatic instantiation and injection, just before the execution of a test method.
テスト クラスで @Tested として注釈が付けられた非最終インスタンス フィールドは、テスト メソッドの実行直前に自動インスタンス化および挿入の対象として考慮されます。
If at this time the field still holds the null reference, an instance will be created using a suitable constructor of the tested class, while making sure its internal dependencies get properly injected (when applicable).
この時点でフィールドにまだ null 参照が保持されている場合は、テスト対象クラスの適切なコンストラクターを使用してインスタンスが作成され、その内部依存関係が適切に挿入されることを確認します (該当する場合)。

In order to inject mocked instances into the tested object, the test class must also contain one or more mock fields or mock parameters declared to be @Injectable.
モックインスタンスをテスト対象オブジェクトに挿入するには、テスト クラスに、@Injectable として宣言された 1 つ以上のモック フィールドまたはモック パラメータも含まれている必要があります。
Mock fields/parameters annotated only with @Mocked or @Capturing are not considered for injection.
@Mocked または @Capturing のみで注釈が付けられたモック フィールド/パラメーターは、インジェクションの対象として考慮されません。
On the other hand, not all injectable fields/parameters need to have mockable types; they can also have primitive or array types.
一方、すべての注入可能なフィールド/パラメータがモック可能な型である必要はなく、プリミティブ型や配列型を持つこともできます。
The following example test class will demonstrate.
次のサンプルテスト クラスで説明します。

class SomeTest {
   @Tested CodeUnderTest tested;
   @Injectable Dependency dep1;
   @Injectable AnotherDependency dep2;
   @Injectable int someIntegralProperty = 123;

   @Test
   void someTestMethod(@Injectable("true") boolean flag, @Injectable("Mary") String name) {
      // Record expectations on mocked types, if needed.
必要に応じて、モック化された型に対する期待を記録します。
tested.exerciseCodeUnderTest(); // Verify expectations on mocked types, if required.
必要に応じて、モック化された型の期待値を確認します。
} }

Note that a non-mockable injectable field/parameter must have a value explicitly specified for it, otherwise the default value would be used.
モック化できない注入可能なフィールド/パラメータには明示的に値を指定する必要があり、そうでない場合はデフォルト値が使用されることに注意してください。
In the case of an injectable field, the value can simply be assigned to the field.
注入可能なフィールドの場合は、値を単純にフィールドに割り当てることができます。
Alternatively, it can be provided in the "value" attribute of @Injectable, which is the only way to specify the value in the case of an injectable test method parameter.
あるいは、@Injectable の "value" 属性で指定することもできます。これは、注入可能なテスト メソッド パラメーターの場合に値を指定する唯一の方法です。

Two forms of injection are supported: constructor injection and field injection.
コンストラクター インジェクションとフィールド インジェクションの 2 つの形式のインジェクションがサポートされています。
In the first case, the tested class must have a constructor which can be satisfied by the injectables and/or tested values made available in the test class.
最初のケースでは、テスト対象のクラスには、テスト クラスで使用可能な注入可能値やテスト済みの値によって満たされるコンストラクターが必要です。
Note that for a given test, the set of available injectable/tested values consists of the set of injectable/tested fields declared as instances fields of the test class plus the set of injectable/tested parameters declared in the test method; therefore, different tests in the same test class can provide different sets of values to be injected into the same tested object.
特定のテストでは、使用可能な注入可能/テスト済み値のセットは、テスト クラスのインスタンス フィールドとして宣言された注入可能/テスト済みフィールドのセットと、テスト メソッドで宣言された注入可能/テスト済みパラメータのセットで構成されることに注意してください。したがって、同じテスト クラス内の異なるテストでは、同じテスト対象オブジェクトに注入される異なる値のセットを提供できます。

Once the tested class is initialized with the chosen constructor, its remaining uninitialized non-final instance fields are considered for injection.
テスト対象のクラスが選択されたコンストラクターで初期化されると、残りの初期化されていない非最終インスタンス フィールドが注入対象として検討されます。
For each such field to be injected, an injectable/tested field of the same type is searched in the test class.
注入される各フィールドについて、同じタイプの注入可能/テスト済みフィールドがテスト クラスで検索されます。
If only one is found, its current value is read and then stored in the injected field.
1 つだけ見つかった場合は、その現在の値が読み取られ、挿入されたフィールドに格納されます。
If there is more than one, the injected field name is used to select between the injectable/tested fields of same type.
複数ある場合は、注入されたフィールド名を使用して、同じタイプの注入可能/テスト済みフィールドを選択します。

5 Recording results for an expectation

For a given method with non-void return type, a return value can be recorded with an assignment to the result field.
void 以外の戻り型を持つ特定のメソッドの場合、戻り値は結果フィールドへの割り当てによって記録できます。
When the method gets called in the replay phase, the specified return value will be returned to the caller.
メソッドが再生フェーズで呼び出されると、指定された戻り値が呼び出し元に返されます。
The assignment to result should appear right after the invocation that identifies the recorded expectation, inside an expectation block.
result への割り当ては、期待値ブロック内で、記録された期待値を識別する呼び出しの直後に出現する必要があります。

If the test instead needs an exception or error to be thrown when the method is invoked, then the result field can still be used: simply assign the desired throwable instance to it.
代わりに、メソッドが呼び出されたときにテストで例外またはエラーをスローする必要がある場合は、結果フィールドを引き続き使用できます。必要なスロー可能なインスタンスをそれに割り当てるだけです。
Note that the recording of exceptions/errors to be thrown is applicable to mocked methods (of any return type) as well as to mocked constructors.
スローされる例外/エラーの記録は、モック化されたコンストラクターだけでなく、モック化されたメソッド (任意の戻り値の型) にも適用されることに注意してください。

Multiple consecutive values to return can be recorded for an expectation, by calling the returns(v1, v2, ...) method.
returns(v1, v2, ...) メソッドを呼び出すことによって、期待値に対して返される複数の連続した値を記録できます。
Alternatively, the same can be achieved by assigning the result field with a list or array containing the consecutive values.
あるいは、連続した値を含むリストまたは配列を結果フィールドに割り当てることによって同じことを実現できます。

The following example test records both types of results for the methods of a mocked DependencyAbc class, to be used when they are invoked from ClassUnderTest.
次のサンプル テストは、ClassUnderTest から呼び出されたときに使用される、モック化された DependencyAbc クラスのメソッドの両方のタイプの結果を記録します。
Lets say the implementation of the class under test goes like this:
テスト対象のクラスの実装は次のようになるとします。

public class ClassUnderTest {
   private final DependencyAbc abc = new DependencyAbc();

   public void doSomething() {
(1)   int n = abc.intReturningMethod();

      for (int i = 0; i < n; i++) {
         String s;

         try {
(2)         s = abc.stringReturningMethod();
         }
         catch (SomeCheckedException e) {
            // somehow handle the exception
何らかの方法で例外を処理する
} // do some other stuff
他のことをする
} } }

A possible test for the doSomething() method could exercise the case where SomeCheckedException gets thrown, after an arbitrary number of successful iterations.
doSomething() メソッドの可能なテストでは、任意の回数の反復が成功した後に SomeCheckedException がスローされるケースを実行できます。
Assuming that we want to record a set of expectations for the interaction between these two classes, we might write the test below.
これら 2 つのクラス間の相互作用に関する一連の期待値を記録したいという場合、以下のようなテストを記述することができます。

@Tested ClassUnderTest cut;

@Test
void doSomethingHandlesSomeCheckedException(@Mocked DependencyAbc abc) throws Exception {
   new Expectations() {{
(1)   abc.intReturningMethod(); result = 3;

(2)   abc.stringReturningMethod();
      returns("str1", "str2");
      result = new SomeCheckedException();
   }};

   cut.doSomething();
}

This test records two expectations.
このテストでは、2 つの期待を記録します。
The first one specifies that intReturningMethod() will return 3 when called.
最初のものは、intReturningMethod() が呼び出されたときに 3 を返すことを指定します。
The second specifies a sequence of three consecutive results for stringReturningMethod(), where the last result happens to be an instance of the desired exception, allowing the test to achieve its goal.
2 番目は、stringReturningMethod() の 3 つの連続する結果のシーケンスを指定します。最後の結果は目的の例外のインスタンスとなり、テストの目的を達成できます。

6 Flexible matching of argument values

When a mocked method/constructor has one or more parameters, a recorded/verified expectation like doSomething(1, "s", true); will only match an invocation in the replay phase if it has equal argument values.
モックされたメソッド/コンストラクターに 1 つ以上のパラメーターがある場合、doSomething(1, "s", true); のような記録/検証された期待値は、引数値が等しい場合にのみ再生フェーズの呼び出しと一致します。
For arguments that are regular objects (not primitives or arrays), the equals(Object) method is used for equality checking.
通常のオブジェクト(プリミティブまたは配列ではない)である引数の場合、equals(Object) メソッドを使用して等価性をチェックします。
For parameters of array type, equality checking extends to individual elements; therefore, two different array instances having the same length in each dimension and equal corresponding elements are considered equal.
配列型のパラメータの場合、等価性チェックは個々の要素にまで及ぶため、各次元の長さが同じで、対応する要素が等しい 2 つの異なる配列インスタンスは等しいとみなされます。

To allow a recorded or verified invocation to match a whole set of replayed invocations with different argument values, we can specify flexible argument matching constraints instead of actual argument values.
記録または検証された呼び出しを、異なる引数値を持つ再生された呼び出しのセット全体と一致させるには、実際の引数値の代わりに柔軟な引数一致制約を指定できます。
This is done by using anyXyz fields and/or withXyz(...) methods, from inside expectation or verification blocks.
これは、期待値または検証ブロック内から、anyXyz フィールドおよび/または withXyz(...) メソッドを使用して行われます。

6.1 Using the "any" fields

The most commonly used argument matching constraints are those that simply match invocations with any value for a given parameter (of the proper parameter type).
最も一般的に使用される引数一致制約は、指定されたパラメータ(適切なパラメータ タイプ)の任意の値を持つ呼び出しを単純に一致させるものです。
For that we have a whole set of special argument matching fields, one for each primitive type (and the corresponding wrapper class), one for strings, and a "universal" one of type Object.
そのために、特別な引数マッチング フィールドのセット全体、各プリミティブ型 (および対応するラッパー クラス) に 1 つ、文字列に 1 つ、および Object 型の「ユニバーサル」フィールドがあります。
The test below demonstrates some uses.
以下のテストでは、いくつかの使用法を示します。

@Tested CodeUnderTest cut;

@Test
void someTestMethod(@Mocked DependencyAbc abc) {
   DataItem item = new DataItem(...);

   new Expectations() {{
      // Will match "voidMethod(String, List)" invocations where the first argument is any string and the second any list.
最初の引数が任意の文字列で、2 番目の引数が任意のリストである "voidMethod(String, List)" 呼び出しに一致します。
abc.voidMethod(anyString, (List<?>) any); }}; cut.doSomething(item); new Verifications() {{ // Matches invocations to the specified method with any value of type long or Long.
指定されたメソッドへの呼び出しを、long 型または Long 型の任意の値で一致させます。
abc.anotherVoidMethod(anyLong); }}; }

Uses of "any" fields must appear at the actual argument positions in the invocation statement, never before.
「any」フィールドの使用は、呼び出しステートメント内の実際の引数の位置に出現する必要があり、それ以前に出現してはなりません。
You can still have regular argument values for other parameters in the same invocation, though.
ただし、同じ呼び出しで他のパラメータに通常の引数値を使用することはできます。
For more details, consult the API documentation from your Java IDE.
詳細については、Java IDE の API ドキュメントを参照してください。

6.2 Using the "with" methods

When recording or verifying an expectation, calls to the withXyz(...) methods can occur for any subset of the arguments passed in the invocation.
期待値を記録または検証する場合、呼び出しで渡された引数の任意のサブセットに対して withXyz(...) メソッドの呼び出しが発生する可能性があります。
They can be freely mixed with regular argument-passing (using literal values, local variables, etc.).
これらは、通常の引数渡し (リテラル値、ローカル変数などを使用) と自由に組み合わせることができます。
The only requirement is that such calls appear inside the recorded/verified invocation statement, rather than before it.
唯一の要件は、そのような呼び出しが、記録/検証された呼び出しステートメントの前ではなく、その内部に現れることです。
It's not possible, for example, to first assign the result of a call to withNotEqual(val) to a local variable and then use the variable in the invocation statement.
たとえば、最初に withNotEqual(val) の呼び出しの結果をローカル変数に割り当て、次にその変数を呼び出しステートメントで使用することはできません。
An example test using some of the "with" methods is shown below.
いくつかの「with」メソッドを使用したテストの例を以下に示します。

@Test
void someTestMethod(@Mocked DependencyAbc abc) {
   DataItem item = new DataItem(...);

   new Expectations() {{
      // Will match "voidMethod(String, List)" invocations with the first argument equal to "str" and the second not null.
最初の引数が "str" に等しく、2 番目の引数が null でない "voidMethod(String, List)" 呼び出しと一致します。
abc.voidMethod("str", (List<?>) withNotNull()); // Will match invocations to DependencyAbc#stringReturningMethod(DataItem, String) with the first argument pointing to "item" and the second one containing "xyz".
最初の引数が「item」を指し、2 番目の引数に「xyz」が含まれる DependencyAbc#stringReturningMethod(DataItem, String) への呼び出しと一致します。
abc.stringReturningMethod(withSameInstance(item), withSubstring("xyz")); }}; cut.doSomething(item); new Verifications() {{ // Matches invocations to the specified method with any long-valued argument.
任意の long 値の引数を持つ指定されたメソッドへの呼び出しを一致させます。
abc.anotherVoidMethod(withAny(1L)); }}; }

There are more "with" methods than shown above.
上記以外にも「with」メソッドは多数あります。
Use your IDE's code completion, and consult the API documentation for more details.
詳細については、IDE のコード補完機能を使用し、API ドキュメントを参照してください。

Besides the several predefined argument matching constraints available in the API, JMockit allows the user to provide custom constraints, through the with(Delegate) method.
API で利用可能ないくつかの定義済み引数一致制約に加えて、JMockit では、with(Delegate) メソッドを通じてユーザーがカスタム制約を提供できます。

7 Specifying invocation count constraints

The number of invocations expected and/or allowed to match a given expectation can be specified through invocation count constraints.
特定の期待値に一致すると予想される呼び出し回数や許可される呼び出し回数は、呼び出し回数制約によって指定できます。
There are three special fields just for that: times, minTimes, and maxTimes.
そのために、times、minTimes、maxTimes という 3 つの特別なフィールドがあります。
They can be used either when recording or when verifying expectations.
記録するときや期待を確認するときに使用できます。
In either case, the method or constructor associated with the expectation will be constrained to receive a number of invocations that falls in the specified range.
どちらの場合でも、期待値に関連付けられたメソッドまたはコンストラクターは、指定された範囲内の呼び出し回数を受け取るように制約されます。
Any invocations less or more than the expected lower or upper limit, respectively, and the test execution will automatically fail.
それぞれ予想される下限値または上限値より少ないまたは多い呼び出しがあった場合、テストの実行は自動的に失敗します。
Lets see some example tests.
いくつかのテスト例を見てみましょう。

@Tested CodeUnderTest cut;

@Test
void someTestMethod(@Mocked DependencyAbc abc) {
   new Expectations() {{
      // By default, at least one invocation is expected, i.e. "minTimes = 1":
デフォルトでは、少なくとも 1 回の呼び出しが想定されます (つまり、「minTimes = 1」)。
new DependencyAbc(); // At least two invocations are expected:
少なくとも 2 回の呼び出しが予想されます。
abc.voidMethod(); minTimes = 2; // 1 to 5 invocations are expected:
1 ~ 5 回の呼び出しが予想されます。
abc.stringReturningMethod(); minTimes = 1; maxTimes = 5; }}; cut.doSomething(); } @Test void someOtherTestMethod(@Mocked DependencyAbc abc) { cut.doSomething(); new Verifications() {{ // Verifies that zero or one invocations occurred, with the specified argument value:
指定された引数値で 0 回または 1 回の呼び出しが発生したことを確認します。
abc.anotherVoidMethod(3); maxTimes = 1; // Verifies the occurrence of at least one invocation with the specified arguments:
指定された引数を使用して少なくとも 1 回の呼び出しが発生したことを確認します。
DependencyAbc.someStaticMethod("test", false); // "minTimes = 1" is implied }}; }

Unlike the result field, each of these three fields can be specified at most once for a given expectation.
結果フィールドとは異なり、これらの 3 つのフィールドはそれぞれ、特定の期待値に対して最大 1 回指定できます。
Any non-negative integer value is valid for any of the invocation count constraints.
呼び出し回数制約のいずれに対しても、負でない整数値が有効です。
If times = 0 or maxTimes = 0 is specified, the first invocation matching the expectation to occur during replay (if any) will cause the test to fail.
times = 0 または maxTimes = 0 が指定されている場合、再生中に発生すると予想される最初の呼び出し (存在する場合) によってテストは失敗します。

8 Explicit verification

Besides specifying invocation count constraints on recorded expectations, we can also verify matching invocations explicitly in verification blocks, after the call to the code under test.
記録された期待値に対して呼び出し回数の制約を指定することに加えて、テスト対象コードの呼び出し後に、検証ブロックで一致する呼び出しを明示的に検証することもできます。

Inside a "new Verifications() {...}" block we can use the same API that's available in a "new Expectations() {...}" block, with the exception of methods and fields used to record return values and thrown exceptions.
「new Verifications() {...}」ブロック内では、戻り値とスローされた例外を記録するために使用されるメソッドとフィールドを除いて、「new Expectations() {...}」ブロックで使用できるものと同じ API を使用できます。
That is, we can freely use the anyXyz fields, the withXyz(...) argument matching methods, and the times, minTimes, and maxTimes invocation count constraint fields.
つまり、anyXyz フィールド、withXyz(...) 引数マッチング メソッド、times、minTimes、maxTimes 呼び出し回数制約フィールドを自由に使用できます。
An example test follows.
テスト例を以下に示します。

@Test
void verifyInvocationsExplicitlyAtEndOfTest(@Mocked Dependency mock) {
   // Nothing recorded here, though it could be.
ここには何も記録されていませんが、記録されている可能性があります。
// Inside tested code:
テストされたコード内:
Dependency dependency = new Dependency(); dependency.doSomething(123, true, "abc-xyz"); // Verifies that Dependency#doSomething(int, boolean, String) was called at least once, with arguments that obey the specified constraints:
指定された制約に従う引数を使用して、Dependency#doSomething(int, boolean, String) が少なくとも 1 回呼び出されたことを確認します。
new Verifications() {{ mock.doSomething(anyInt, true, withPrefix("abc")); }}; }

Note that, by default, a verification checks that at least one matching invocation occurred during replay.
デフォルトでは、検証では再生中に少なくとも 1 つの一致する呼び出しが発生したかどうかがチェックされることに注意してください。
When we need to verify an exact number of invocations (including 1), the times = n constraint must be specified.
呼び出し回数の正確な数 (1 を含む) を検証する必要がある場合は、times = n 制約を指定する必要があります。

8.1 Verification in order

Regular verification blocks created with the Verifications class are unordered.
Verifications クラスで作成された通常の検証ブロックは順序付けられていません。
The actual relative order in which aMethod() and anotherMethod() were called during the replay phase is not verified, but only that each method was executed at least once.
再生フェーズ中に aMethod() と anotherMethod() が呼び出された実際の相対順序は検証されず、各メソッドが少なくとも 1 回実行されたことのみが検証されます。
If you want to verify the relative order of invocations, then a "new VerificationsInOrder() {...}" block must be used instead.
呼び出しの相対的な順序を検証する場合は、代わりに「new VerificationsInOrder() {...}」ブロックを使用する必要があります。
Inside this block, simply write invocations to one or more mocked types in the order they are expected to have occurred.
このブロック内では、1 つ以上のモック化された型への呼び出しを、発生すると予想される順序で記述するだけです。

@Test
void verifyingExpectationsInOrder(@Mocked DependencyAbc abc) {
   // Somewhere inside the tested code:
テストされたコード内のどこか:
abc.aMethod(); abc.doSomething("blah", 123); abc.anotherMethod(5); ... new VerificationsInOrder() {{ // The order of these invocations must be the same as the order of occurrence during replay of the matching invocations.
これらの呼び出しの順序は、一致する呼び出しの再生時の発生順序と同じである必要があります。
abc.aMethod(); abc.anotherMethod(anyInt); }}; }

Note that the call abc.doSomething(...) was not verified in the test, so it could have occurred at any time (orv not at all).
呼び出し abc.doSomething(...) はテストで検証されていないため、いつでも発生する可能性があることに注意してください (またはまったく発生しない可能性があります)。

8.2 Full verification

Sometimes it may be desired to have all invocations to the mocked types/instances involved in a test verified.
場合によっては、テストに関係するモック化された型/インスタンスへのすべての呼び出しを検証することが望ましい場合があります。
In such cases, a "new FullVerifications() {...}" block will make sure that no invocations are left unverified.
このような場合、「new FullVerifications() {...}」ブロックにより、検証されていない呼び出しが残らないようにします。

@Test
void verifyAllInvocations(@Mocked Dependency mock) {
   // Code under test included here for easy reference:
簡単に参照できるように、テスト対象のコードをここに含めます。
mock.setSomething(123); mock.setSomethingElse("anotherValue"); mock.setSomething(45); mock.save(); new FullVerifications() {{ mock.setSomething(anyInt); // verifies two actual invocations
2つの実際の呼び出しを検証する
mock.setSomethingElse(anyString); mock.save(); // if this verification (or any other above) is removed the test will fail
この検証(または上記の他の検証)が削除されると、テストは失敗します。
}}; }

9 Delegates: specifying custom results

To decide the result of a recorded expectation based on the arguments it receives at replay time, we can use a Delegate object, as exemplified below.
再生時に受け取る引数に基づいて記録された期待値の結果を決定するには、以下に例示するように Delegate オブジェクトを使用できます。

@Tested CodeUnderTest cut;

@Test
void delegatingInvocationsToACustomDelegate(@Mocked DependencyAbc anyAbc) {
   new Expectations() {{
      anyAbc.intReturningMethod(anyInt, anyString);
      result = new Delegate() {
         int aDelegateMethod(int i, String s) {
            return i == 1 ? i : s.length();
         }
      };
   }};

   // Calls to "intReturningMethod(int, String)" will execute the delegate method above.
「intReturningMethod(int, String)」を呼び出すと、上記のデリゲート メソッドが実行されます。
cut.doSomething(); }

The Delegate interface is empty, being used simply to tell JMockit that actual invocations at replay time should be delegated to the "delegate" method in the assigned object.
Delegate インターフェースは空で、再生時の実際の呼び出しを割り当てられたオブジェクトの「delegate」メソッドに委任する必要があることを JMockit に伝えるためにのみ使用されます。
This method can have any name, provided it is the only non-private method in the delegate object.
このメソッドは、デリゲート オブジェクト内の唯一の非プライベート メソッドであれば、任意の名前を付けることができます。
As for the parameters of the delegate method, they should either match the parameters of the recorded method, or there should be none.
デリゲート メソッドのパラメーターについては、記録されたメソッドのパラメーターと一致するか、またはパラメーターが存在しない必要があります。
In any case, the delegate method is allowed to have an additional parameter of type Invocation as its first parameter.
いずれの場合でも、デリゲート メソッドでは、最初のパラメーターとして Invocation 型の追加パラメーターを持つことができます。
The Invocation object received during replay will provide access to the invoked instance and the actual invocation arguments, along with other abilities.
再生中に受信した Invocation オブジェクトは、呼び出されたインスタンスと実際の呼び出し引数へのアクセス、およびその他の機能を提供します。
The return type of a delegate method doesn't have to be the same as the recorded method, although it should be compatible in order to avoid a ClassCastException later.
デリゲート メソッドの戻り値の型は、記録されたメソッドと同じである必要はありませんが、後で ClassCastException を回避するために互換性がある必要があります。

Constructors can also be handled through delegate methods.
コンストラクターはデリゲート メソッドを通じて処理することもできます。
The following example test shows a constructor invocation being delegated to a method which conditionally throws an exception.
次のサンプルテストは、条件付きで例外をスローするメソッドに委任されるコンストラクター呼び出しを示しています。

@Test
void delegatingConstructorInvocations(@Mocked Collaborator anyCollaboratorInstance) {
   new Expectations() {{
      new Collaborator(anyInt);
      result = new Delegate() {
         void delegate(int i) { if (i < 1) throw new IllegalArgumentException(); }
      };
   }};

   // The first instantiation using "Collaborator(int)" will execute the delegate above.
「Collaborator(int)」を使用した最初のインスタンス化では、上記のデリゲートが実行されます。
new Collaborator(4); }

10 Capturing invocation arguments for verification

Invocation arguments can be captured for later verification through a set of special "withCapture(...)" methods.
呼び出し引数は、特別な "withCapture(...)" メソッドのセットを介して後で検証するためにキャプチャできます。
There are three different cases, each with its own specific capturing method:
3 つの異なるケースがあり、それぞれに独自のキャプチャ方法があります。

  1. verification of arguments passed to a mocked method, in a single invocation: T withCapture();
    単一の呼び出しで、モックメソッドに渡される引数の検証: T withCapture();
  2. verification of arguments passed to a mocked method, in multiple invocations: T withCapture(List<T>);
    複数の呼び出しで、モックメソッドに渡される引数の検証: T withCapture(List<T>);
  3. verification of arguments passed to a mocked constructor: List<T> withCapture(T).
    モックされたコンストラクタに渡される引数の検証: List<T> withCapture(T)。

10.1 Capturing arguments from a single invocation

To capture arguments from a single invocation to a mocked method or constructor, we use withCapture(), as the following example test demonstrates.
モックされたメソッドまたはコンストラクターへの単一の呼び出しから引数をキャプチャするには、次のサンプルテストに示すように、withCapture() を使用します。

@Test
void capturingArgumentsFromSingleInvocation(@Mocked Collaborator mock) {
   // Inside tested code:
テストされたコード内:
... new Collaborator().doSomething(0.5, new int[2], "test"); // Back in test code:
テストコードに戻ります:
new Verifications() {{ double d; String s; mock.doSomething(d = withCapture(), null, s = withCapture()); assertTrue(d > 0.0); assertTrue(s.length() > 1); }}; }

The withCapture() method can only be used in verification blocks.
withCapture() メソッドは検証ブロックでのみ使用できます。
Typically, we use it when a single matching invocation is expected to occur; if more than one such invocation occurs, however, the last one to occur overwrites the values captured by previous ones.
通常、単一の一致する呼び出しが発生すると予想される場合にこれを使用します。ただし、そのような呼び出しが複数回発生した場合は、最後に発生した呼び出しによって、以前の呼び出しによってキャプチャされた値が上書きされます。
It is particularly useful with parameters of a complex type (think a JPA @Entity), which may contain several items whose values need to be checked.
これは、値を確認する必要がある複数の項目が含まれる可能性がある複合型のパラメータ (JPA @Entity など) で特に役立ちます。

10.2 Capturing arguments from multiple invocations

If multiple invocations to a mocked method or constructor are expected, and we want to capture values for all of them, then the withCapture(List) method should be used instead, as in the example below.
モックされたメソッドまたはコンストラクターへの複数の呼び出しが予想され、それらすべての値をキャプチャする場合は、次の例のように、代わりに withCapture(List) メソッドを使用する必要があります。

@Test
void capturingArgumentsFromMultipleInvocations(@Mocked Collaborator mock) {
   // Inside tested code:
テストされたコード内:
mock.doSomething(dataObject1); mock.doSomething(dataObject2); ... // Back in test code:
テストコードに戻ります:
new Verifications() {{ List<DataObject> dataObjects = new ArrayList<>(); mock.doSomething(withCapture(dataObjects)); assertEquals(2, dataObjects.size()); DataObject data1 = dataObjects.get(0); DataObject data2 = dataObjects.get(1); // Perform arbitrary assertions on data1 and data2.
data1 と data2 に対して任意のアサーションを実行します。
}}; }

Differently from withCapture(), the withCapture(List) overload can also be used in expectation recording blocks.
withCapture() とは異なり、withCapture(List) オーバーロードは期待値記録ブロックでも使用できます。

10.3 Capturing new instances

Finally, we can capture the new instances of a mocked class that got created during the test.
最後に、テスト中に作成されたモッククラスの新しいインスタンスをキャプチャできます。

@Test
void capturingNewInstances(@Mocked Person mockedPerson) {
   // From the code under test:
テスト対象のコードから:
dao.create(new Person("Paul", 10)); dao.create(new Person("Mary", 15)); dao.create(new Person("Joe", 20)); ... // Back in test code:
テストコードに戻ります:
new Verifications() {{ // Captures the new instances created with a specific constructor.
特定のコンストラクターで作成された新しいインスタンスをキャプチャします。
List<Person> personsInstantiated = withCapture(new Person(anyString, anyInt)); // Now captures the instances of the same type passed to a method.
メソッドに渡された同じタイプのインスタンスをキャプチャするようになりました。
List<Person> personsCreated = new ArrayList<>(); dao.create(withCapture(personsCreated)); // Finally, verifies both lists are the same.
最後に、両方のリストが同じであることを確認します。
assertEquals(personsInstantiated, personsCreated); }}; }

11 Cascading mocks

When using complex APIs where functionality is distributed through many different objects, it is not uncommon to see chained invocations of the form obj1.getObj2(...).getYetAnotherObj().doSomething(...).
機能が多くの異なるオブジェクトに分散されている複雑な API を使用する場合、obj1.getObj2(...).getYetAnotherObj().doSomething(...) という形式の連鎖呼び出しを目にすることは珍しくありません。
In such cases it may be necessary to mock all objects/classes in the chain, starting with obj1.
このような場合、obj1 から始めて、チェーン内のすべてのオブジェクト/クラスをモックする必要がある可能性があります。

All three mocking annotations provide this ability.
3 つのモック注釈すべてがこの機能を提供します。
The following test shows a basic example, using the java.net and java.nio APIs.
次のテストは、java.net および java.nio API を使用した基本的な例を示しています。

@Test
void recordAndVerifyExpectationsOnCascadedMocks(
   @Mocked Socket anySocket, // will match any new Socket object created during the test
   @Mocked SocketChannel cascadedChannel // will match cascaded instances
) throws Exception {
   new Expectations() {{
      // Calls to Socket#getChannel() will automatically return a cascaded SocketChannel; such an instance will be the same as the second mock parameter, allowing us to use it for expectations that will match all cascaded channel instances:
Socket#getChannel() を呼び出すと、カスケードされた SocketChannel が自動的に返されます。このようなインスタンスは 2 番目のモック パラメータと同じになり、すべてのカスケードされたチャネル インスタンスに一致する期待値に使用できます。
cascadedChannel.isConnected(); result = false; }}; // Inside production code:
製品コード内部:
Socket sk = new Socket(); // mocked as "anySocket" SocketChannel ch = sk.getChannel(); // mocked as "cascadedChannel" if (!ch.isConnected()) { SocketAddress sa = new InetSocketAddress("remoteHost", 123); ch.connect(sa); } InetAddress adr1 = sk.getInetAddress(); // returns a newly created InetAddress instance
新しく作成されたInetAddressインスタンスを返します
InetAddress adr2 = sk.getLocalAddress(); // returns another new instance
別の新しいインスタンスを返す
... // Back in test code:
テストコードに戻ります:
new Verifications() {{ cascadedChannel.connect((SocketAddress) withNotNull()); }}; }

In the test above, calls to eligible methods in the mocked Socket class will return a cascaded mock object whenever they occur during the test.
上記のテストでは、モックされた Socket クラス内の適格なメソッドの呼び出しは、テスト中に発生するたびに、カスケードされたモック オブジェクトを返します。
The cascaded mock will allow further cascading, so a null reference will never be obtained from methods which return object references (except for non-eligible return types Object or String which will return null, or collection types which will return a non-mocked empty collection).
カスケードされたモックではさらにカスケードが可能になるため、オブジェクト参照を返すメソッドから null 参照が取得されることはありません (null を返す不適格な戻り値の型 Object または String、またはモック化されていない空のコレクションを返すコレクション型を除く)。

Unless there is an available mocked instance from a mock field/parameter (such as cascadedChannel above), a new cascaded instance will get created from the first call to each mocked method.
モック フィールド/パラメーター (上記の cascadedChannel など) から使用可能なモック インスタンスがない限り、各モック メソッドへの最初の呼び出しから新しいカスケード インスタンスが作成されます。
In the example above, the two different methods with the same InetAddress return type will create and return different cascaded instances; the same method will always return the same cascaded instance, though.
上記の例では、同じ InetAddress 戻り値の型を持つ 2 つの異なるメソッドが、異なるカスケード インスタンスを作成して返します。ただし、同じメソッドは常に同じカスケード インスタンスを返します。

New cascaded instances are created with @Injectable semantics, so as to not affect other instances of the same type that may exist during the test.
新しいカスケードインスタンスは、テスト中に存在する可能性のある同じタイプの他のインスタンスに影響を与えないように、@Injectable セマンティクスを使用して作成されます。

Finally, it's worth noting that, if necessary, cascaded instances can be replaced with non-mocked ones, with a different mocked instance, or not be returned at all; for that, record an expectation which assigns the result field with the desired instance to be returned, or with null if no such instance is desired.
最後に、必要に応じて、カスケードされたインスタンスを非モック インスタンスや別のモック インスタンスに置き換えたり、まったく返さないようにしたりできることにも注意してください。そのためには、返されるインスタンスを結果フィールドに割り当てる期待値、またはそのようなインスタンスが不要な場合は null を割り当てる期待値を記録します。

11.1 Cascading static factory methods

Cascading is quite useful in scenarios where a mocked class contains static factory methods.
カスケード機能は、モックされたクラスに静的ファクトリ メソッドが含まれているシナリオでは非常に便利です。
In the following example test, lets say we want to mock the javax.faces.context.FacesContext class from JSF (Java EE).
次のサンプルテストでは、JSF (Java EE) の javax.faces.context.FacesContext クラスをモックするとします。

@Test
void postErrorMessageToUIForInvalidInputFields(@Mocked FacesContext jsf) {
   // Set up invalid inputs, somehow.
何らかの方法で無効な入力を設定します。
// Code under test which validates input fields from a JSF page, adding error messages to the JSF context in case of validation failures.
JSF ページからの入力フィールドを検証し、検証が失敗した場合に JSF コンテキストにエラー メッセージを追加するテスト対象のコード。
FacesContext ctx = FacesContext.getCurrentInstance(); if (some input is invalid) { ctx.addMessage(null, new FacesMessage("Input xyz is invalid: blah blah...")); } ... // Test code: verify appropriate error message was added to context.
テスト コード: 適切なエラー メッセージがコンテキストに追加されたことを確認します。
new Verifications() {{ FacesMessage msg; jsf.addMessage(null, msg = withCapture()); assertTrue(msg.getSummary().contains("blah blah")); }}; }

What's interesting in the test above is that we never have to worry about FacesContext.getCurrentInstance(), as the "jsf" mocked instance gets automatically returned.
上記のテストで興味深いのは、「jsf」モックインスタンスが自動的に返されるため、FacesContext.getCurrentInstance() について心配する必要がないことです。

11.2 Cascading self-returning methods

Another scenario where cascading tends to help is when code under test uses a "fluent interface", where a "builder" object returns itself from most of its methods.
カスケードが役立つ傾向があるもう 1 つのシナリオは、テスト対象のコードが「流れるようなインターフェース」を使用し、「ビルダー」オブジェクトがほとんどのメソッドから自分自身を返す場合です。
So, we end up with a method call chain which produces some final object or state.
したがって、最終的なオブジェクトまたは状態を生成するメソッド呼び出しチェーンが完成します。
In the example test below we mock the java.lang.ProcessBuilder class.
以下のサンプルテストでは、java.lang.ProcessBuilder クラスをモックします。

@Test
void createOSProcessToCopyTempFiles(@Mocked ProcessBuilder pb) throws Exception {
   // Code under test creates a new process to execute an OS-specific command.
テスト対象のコードは、OS 固有のコマンドを実行するための新しいプロセスを作成します。
String cmdLine = "copy /Y *.txt D:\\TEMP"; File wrkDir = new File("C:\\TEMP"); Process copy = new ProcessBuilder().command(cmdLine).directory(wrkDir).inheritIO().start(); int exit = copy.waitFor(); ... // Verify the desired process was created with the correct command.
正しいコマンドを使用して目的のプロセスが作成されたことを確認します。
new Verifications() {{ pb.command(withSubstring("copy")).start(); }}; }

Above, methods command(...), directory(...), and inheritIO() configure the process to be created, while start() finally creates it.
上記では、command(...)、directory(...)、inheritIO() メソッドが作成するプロセスを構成し、start() が最終的にプロセスを作成します。
The mocked process builder object automatically returns itself ("pb") from these calls, while also returning a new mocked Process from the call to start().
モックされたプロセス ビルダー オブジェクトは、これらの呼び出しから自動的に自分自身 ("pb") を返すと同時に、start() の呼び出しから新しいモックされたプロセスも返します。

12 Matching invocations to specific instances

Previously, we explained that an expectation recorded on a mocked instance, such as "abc.someMethod();" would actually match invocations to DependencyAbc#someMethod() on any instance of the mocked DependencyAbc class.
以前、"abc.someMethod();" などのモックインスタンスに記録された期待値は、実際には、モックされた DependencyAbc クラスの任意のインスタンスでの DependencyAbc#someMethod() の呼び出しと一致することを説明しました。
In most cases, tested code uses a single instance of a given dependency, so this won't really matter and can be safely ignored, whether the mocked instance is passed into the code under test or created inside it.
ほとんどの場合、テスト対象のコードは特定の依存関係の単一のインスタンスを使用するため、モック化されたインスタンスがテスト対象のコードに渡されるか、その内部で作成されるかに関係なく、これは実際には問題にはならず、無視しても問題ありません。
But what if we need to verify that invocations occur on a specific instance, between several ones that happen to be used in the code under test?
しかし、テスト対象のコードで使用されている複数のインスタンスの間で、特定のインスタンスで呼び出しが発生することを検証する必要がある場合はどうでしょうか?
Also, what if only one or a few instances of the mocked class should actually be mocked, with other instances of the same class remaining unmocked?
また、モックされたクラスの 1 つまたは少数のインスタンスのみが実際にモックされ、同じクラスの他のインスタンスはモックされない場合はどうなるでしょうか?
(This second case tends to occur more often when classes from the standard Java libraries, or from other third-party libraries, are mocked.)
(この 2 番目のケースは、標準 Java ライブラリまたはその他のサードパーティ ライブラリのクラスがモック化される場合に、より頻繁に発生する傾向があります。)
The API provides a mocking annotation, @Injectable, which will only mock one instance of the mocked type, leaving others unaffected.
API は、モック化された型のインスタンスを 1 つだけモックし、他のインスタンスには影響を与えないモック アノテーション @Injectable を提供します。
Additionally, we have a couple ways to constrain the matching of expectations to specific @Mocked instances, while still mocking all instances of the mocked class.
さらに、モックされたクラスのすべてのインスタンスをモックしながら、特定の @Mocked インスタンスへの期待値の一致を制限する方法がいくつかあります。

12.1 Injectable mocked instances

Suppose we need to test code which works with multiple instances of a given class, some of which we want to mock.
特定のクラスの複数のインスタンスで動作するコードをテストする必要があり、そのうちのいくつかをモック化する必要があるとします。
If an instance to be mocked can be passed or injected into the code under test, then we can declare an @Injectable mock field or mock parameter for it.
モックするインスタンスをテスト対象のコードに渡したり挿入したりできる場合は、そのための @Injectable モック フィールドまたはモック パラメータを宣言できます。
This @Injectable instance will be an "exclusive" mocked instance; any other instance of the same mocked type, unless obtained from a separate mock field/parameter, will remain as a regular, non-mocked instance.
この @Injectable インスタンスは「排他的」なモック インスタンスになります。同じモック タイプの他のインスタンスは、別のモック フィールド/パラメータから取得されない限り、通常の非モック インスタンスとして残ります。

When using @Injectable, static methods and constructors are also excluded from being mocked.
@Injectable を使用する場合、静的メソッドとコンストラクターもモックから除外されます。
After all, a static method is not associated with any instance of the class, while a constructor is only associated with a newly created (and therefore different) instance.
結局のところ、静的メソッドはクラスのインスタンスに関連付けられていませんが、コンストラクターは新しく作成された (したがって異なる) インスタンスにのみ関連付けられています。

For an example, lets say we have the following class to be tested.
たとえば、次のクラスをテストするとします。

public final class ConcatenatingInputStream extends InputStream {
   private final Queue<InputStream> sequentialInputs;
   private InputStream currentInput;

   public ConcatenatingInputStream(InputStream... sequentialInputs) {
      this.sequentialInputs = new LinkedList<InputStream>(Arrays.asList(sequentialInputs));
      currentInput = this.sequentialInputs.poll();
   }

   @Override
   public int read() throws IOException {
      if (currentInput == null) return -1;

      int nextByte = currentInput.read();

      if (nextByte >= 0) {
         return nextByte;
      }

      currentInput = sequentialInputs.poll();
      return read();
   }
}

This class could easily be tested without mocking by using ByteArrayInputStream objects for input, but lets say we want to make sure that the InputStream#read() method is properly invoked on each input stream passed in the constructor.
このクラスは、入力に ByteArrayInputStream オブジェクトを使用することで、モックなしで簡単にテストできますが、コンストラクターで渡される各入力ストリームで InputStream#read() メソッドが適切に呼び出されることを確認したいとします。
The following test will achieve this.
次のテストでこれが実現されます。

@Test
void concatenateInputStreams(@Injectable InputStream input1, @Injectable InputStream input2) throws Exception {
   new Expectations() {{
      input1.read(); returns(1, 2, -1);
      input2.read(); returns(3, -1);
   }};

   InputStream concatenatedInput = new ConcatenatingInputStream(input1, input2);
   byte[] buf = new byte[3];
   concatenatedInput.read(buf);

   assertArrayEquals(new byte[] {1, 2, 3}, buf);
}

Note that the use of @Injectable is indeed necessary here, since the class under test extends the mocked class, and the method called to exercise ConcatenatingInputStream is actually defined in the base InputStream class.
テスト対象のクラスはモック クラスを拡張し、ConcatenatingInputStream を実行するために呼び出されるメソッドは実際には基本 InputStream クラスで定義されているため、ここでは @Injectable の使用が実際に必要であることに注意してください。
If InputStream was mocked "normally", the read(byte[]) method would always be mocked, regardless of the instance on which it is called.
InputStream が「通常」モック化されている場合、read(byte[]) メソッドは、呼び出されるインスタンスに関係なく、常にモック化されます。

12.2 Declaring multiple mocked instances

When using @Mocked or @Capturing (and not @Injectable on the same mock field/parameter), we can still match replay invocations to expectations recorded on specific mocked instances.
@Mocked または @Capturing を使用する場合 (同じモック フィールド/パラメーターで @Injectable を使用しない場合)、リプレイ呼び出しを特定のモック インスタンスに記録された期待値と一致させることができます。
For that, we simply declare multiple mock fields or parameters of the same mocked type, as the next example shows.
そのためには、次の例に示すように、同じモック型の複数のモック フィールドまたはパラメーターを宣言するだけです。

@Test
void matchOnMockInstance(@Mocked Collaborator mock, @Mocked Collaborator otherInstance) {
   new Expectations() {{ mock.getValue(); result = 12; }};

   // Exercise code under test with mocked instance passed from the test:
テストから渡されたモックインスタンスを使用して、テスト対象のコードを実行します。
int result = mock.getValue(); assertEquals(12, result); // If another instance is created inside code under test...
テスト対象のコード内に別のインスタンスが作成された場合...
Collaborator another = new Collaborator(); // ...we won't get the recorded result, but the default one:
...記録された結果ではなく、デフォルトの結果が取得されます。
assertEquals(0, another.getValue()); }

The test above will only pass if the tested code (here embedded in the test method itself, for brevity) invokes getValue() on the exact same instance on which the recording invocation was made.
上記のテストは、テスト対象のコード (ここでは簡潔にするためにテスト メソッド自体に埋め込まれています) が、記録呼び出しが行われたのとまったく同じインスタンスで getValue() を呼び出す場合にのみ合格します。
This is typically useful when the code under test makes calls on two or more different instances of the same type, and the test wants to verify that a particular invocation occurred on the expected instance.
これは通常、テスト対象のコードが同じタイプの 2 つ以上の異なるインスタンスを呼び出し、テストで特定の呼び出しが予期されるインスタンスで発生したことを確認する場合に役立ちます。

12.3 Instances created with a given constructor

For future instances that will later get created by code under test, there is a way we can match invocations on them to separate recorded expectations (assuming a test needs varying behavior from said instances).
テスト対象のコードによって後で作成される将来のインスタンスについては、それらの呼び出しを一致させて、記録された期待値を分離する方法があります (テストでは、そのインスタンスとは異なる動作が必要であると想定)。
This is done by recording expectations on specific constructor invocations of the mocked class, and then simply using the new instances obtained from such "new" expressions when recording expectations on their instance methods.
これは、モックされたクラスの特定のコンストラクター呼び出しに対する期待値を記録し、インスタンス メソッドに対する期待値を記録するときに、そのような「新しい」式から取得された新しいインスタンスを単純に使用することによって行われます。
Lets see an example.
例を見てみましょう。

@Test
void newCollaboratorsWithDifferentBehaviors(@Mocked Collaborator anyCollaborator) {
   // Record different behaviors for each set of instances:
インスタンスのセットごとに異なる動作を記録します。
new Expectations() {{ // One set, for instances created with "a value":
「値」で作成されたインスタンス用の 1 セット:
Collaborator col1 = new Collaborator("a value"); col1.doSomething(anyInt); result = 123; // Another set, for instances created with "another value":
「別の値」で作成されたインスタンス用の別のセット:
Collaborator col2 = new Collaborator("another value"); col2.doSomething(anyInt); result = new InvalidStateException(); }}; // Code under test:
テスト対象コード:
new Collaborator("a value").doSomething(5); // will return 123
123を返します
... new Collaborator("another value").doSomething(0); // will throw the exception
例外が発生します
... }

In the above test, we declare a mock field or mock parameter of the desired class, using @Mocked.
上記のテストでは、@Mocked を使用して、目的のクラスのモック フィールドまたはモック パラメーターを宣言します。
This mock field/parameter, however, is not used when recording expectations; instead, we use the instances created on instantiation recordings to record further expectations on instance methods.
ただし、このモック フィールド/パラメーターは期待値を記録するときには使用されません。代わりに、インスタンス化記録で作成されたインスタンスを使用して、インスタンス メソッドに関するさらなる期待値を記録します。
The future instances created with matching constructor invocations will map to those recorded instances.
一致するコンストラクター呼び出しで作成される将来のインスタンスは、記録されたインスタンスにマップされます。
Also, note that it's not necessarily a one-to-one mapping, but a many-to-one mapping, from potentially many future instances to a single instance used for recorded expectations.
また、これは必ずしも 1 対 1 のマッピングではなく、潜在的に多数の将来のインスタンスから、記録された期待値に使用される単一のインスタンスへの多対 1 のマッピングであることに注意してください。

13 Partial mocking

By default, all methods which can be called on a mocked instance get mocked.
デフォルトでは、モックインスタンスで呼び出すことができるすべてのメソッドがモック化されます。
This is appropriate for most tests, but in some situations we might need to select only certain methods to be mocked.
これはほとんどのテストに適していますが、状況によっては、モックする特定のメソッドのみを選択する必要がある場合があります。
Methods not mocked in an otherwise mocked instance will execute normally when called.
モックされたインスタンス内でモックされていないメソッドは、呼び出されると通常どおり実行されます。

When an object is partially mocked, JMockit decides whether to execute the real implementation of a method as it gets called from the code under test, based on which expectations were recorded and which were not.
オブジェクトが部分的にモック化されると、JMockit は、どの期待が記録されたか、どの期待が記録されなかったかに基づいて、テスト対象のコードから呼び出されたときにメソッドの実際の実装を実行するかどうかを決定します。
The following example tests will demonstrate it.
次の例のテストでそれを実証します。

class PartialMockingTest {
   static class Collaborator {
      final int value;

      Collaborator(int value) { this.value = value; }

      int getValue() { return value; }
      final boolean simpleOperation(int a, String b, Date c) { return true; }
      void doSomething() { ... }
   }

   @Test
   void partiallyMockingASingleInstance() {
      Collaborator collaborator = new Collaborator(2);

      new Expectations(collaborator) {{ // one or more instances to be partially mocked
部分的にモックされる1つ以上のインスタンス
collaborator.getValue(); result = 123; collaborator.simpleOperation(1, "", null); result = false; }}; // Mocked (instance methods recorded on one of the given instances):
モック(指定されたインスタンスの 1 つに記録されたインスタンス メソッド):
assertEquals(123, collaborator.getValue()); assertFalse(collaborator.simpleOperation(1, "", null)); // Not mocked (unrecorded instance methods, static methods, constructors, and different instances):
モック化されていない (記録されていないインスタンス メソッド、静的メソッド、コンストラクター、および異なるインスタンス):
collaborator.doSomething(); assertEquals(45, new Collaborator(45).getValue()); } }

As shown above, the Expectations(Object...) constructor accepts one or more objects to be partially mocked.
上記のように、Expectations(Object...) コンストラクターは、部分的にモックされる 1 つ以上のオブジェクトを受け入れます。
In case a test wants to partially mock the constructors and/or static methods of a class, a MockUp (from the Faking API) would have to be used.
テストでクラスのコンストラクターや静的メソッドを部分的にモック化する場合は、MockUp (Faking API から) を使用する必要があります。

Notice that in this example test there is no mock field or mock parameter - so, the partial mocking constructor effectively provides yet another way to apply mocking.
この例のテストにはモック フィールドやモック パラメーターが存在しないことに注意してください。そのため、部分的なモック コンストラクターは、モックを適用する別の方法を効果的に提供します。

It should be noted that, when we request an instance to be partially mocked, it can also have invocations verified on it, even if the verified methods were not recorded.
インスタンスを部分的にモックするように要求すると、検証されたメソッドが記録されていない場合でも、そのインスタンスに対する呼び出しが検証される可能性があることに注意してください。
For example, consider the following test.
たとえば、次のテストを考えてみましょう。

@Test
void partiallyMockingAnObjectJustForVerifications() {
   Collaborator collaborator = new Collaborator(123);

   new Expectations(collaborator) {};

   // No expectations were recorded, so nothing will be mocked.
期待は記録されていないので、嘲笑されることはありません。
int value = collaborator.getValue(); // value == 123 collaborator.simpleOperation(45, "testing", new Date()); ... // Unmocked methods can still be verified:
モック化されていないメソッドも検証できます:
new Verifications() {{ c1.simpleOperation(anyInt, anyString, (Date) any); }}; }

Finally, a simpler way to apply partial mocking to a tested class is to have a field in the test class annotated as both @Tested (see section below) and @Mocked.
最後に、テスト対象クラスに部分的なモックを適用するより簡単な方法は、テスト クラスのフィールドに @Tested (以下のセクションを参照) と @Mocked の両方のアノテーションを付けることです。
In this case, the tested object is not passed to the Expectations constructor, but we still need to record expectations on any methods requiring mocked results.
この場合、テスト対象のオブジェクトは Expectations コンストラクターに渡されませんが、モック結果を必要とするすべてのメソッドの期待値を記録する必要があります。

14 Mocking unspecified implementation classes

Our discussion of this feature will be based on the (contrived) code below.
この機能に関する説明は、以下の(架空の)コードに基づいて行います。

public interface Service { int doSomething(); }
final class ServiceImpl implements Service { public int doSomething() { return 1; } }

public final class TestedUnit {
   private final Service service1 = new ServiceImpl();
   private final Service service2 = new Service() { public int doSomething() { return 2; } };

   public int businessOperation() {
      return service1.doSomething() + service2.doSomething();
   }
}

The method we want to test, businessOperation(), uses classes that implement a separate interface, Service.
テストするメソッド businessOperation() は、別のインターフェース Service を実装するクラスを使用します。
One of these implementations is defined through an anonymous inner class, which is completely inaccessible (except for the use of Reflection) from client code.
これらの実装の 1 つは匿名の内部クラスを通じて定義されており、クライアント コードからは完全にアクセスできません (リフレクションを使用する場合を除く)。

Given a base type (be it an interface, an abstract class, or any sort of base class), we can write a test which only knows about the base type but where all implementing/extending implementation classes get mocked.
基本型 (インターフェース、抽象クラス、またはあらゆる種類の基本クラス) が指定されると、基本型のみを認識し、実装/拡張するすべての実装クラスがモック化されるテストを作成できます。
To do so, we declare a "capturing" mocked type which refers only to the known base type.
これを行うには、既知の基本型のみを参照する「キャプチャ」モック型を宣言します。
Not only will implementation classes already loaded by the JVM get mocked, but also any additional classes that happen to get loaded by the JVM during later test execution.
JVM によってすでにロードされている実装クラスだけでなく、後のテスト実行中に JVM によってロードされる追加のクラスもモック化されます。
This ability is activated by the @Capturing annotation, which can be applied to mock fields and mock parameters, as demonstrated below.
この機能は @Capturing アノテーションによってアクティブ化され、以下に示すように、モック フィールドとモック パラメーターに適用できます。

final class UnitTest {
   @Capturing Service anyService;

   @Test
   void mockingImplementationClassesFromAGivenBaseType() {
      new Expectations() {{ anyService.doSomething(); returns(3, 4); }};

      int result = new TestedUnit().businessOperation();

      assertEquals(7, result);
   }
}

In the test above, two return values are specified for the Service#doSomething() method.
上記のテストでは、Service#doSomething() メソッドに 2 つの戻り値が指定されています。
This expectation will match all invocations to this method, regardless of the actual instance on which the invocation occurs, and regardless of the actual class implementing the method.
この期待は、呼び出しが発生する実際のインスタンスや、メソッドを実装する実際のクラスに関係なく、このメソッドへのすべての呼び出しに一致します。