@@ -819,30 +819,54 @@ sut.VerifyMock.SetProtectedIndexer(It.Is(0), It.Is(42)).Once();
819819
820820### Advanced callback features
821821
822- #### Conditional callbacks
822+ #### Conditional callbacks ( ` When ` )
823823
824824Execute callbacks conditionally based on the zero-based invocation counter using ` .When() ` :
825825
826826``` csharp
827827sut .SetupMock .Method .Dispense (It .Is (" Dark" ), It .IsAny <int >())
828- .Do (() => Console .WriteLine (" Called!" ))
829- .When (count => count >= 2 ); // The first two calls are skipped
828+ .Do (() => Console .WriteLine (" Called!" )).When (count => count >= 2 ); // The first two calls are skipped
830829```
831830
832- #### Frequency control
831+ #### Limit invocations ( ` Only ` )
833832
834- Control how many times a callback executes :
833+ Control after how many times a callback should no longer be executed :
835834
836835``` csharp
837836// Execute up to 3 times
838837sut .SetupMock .Method .Dispense (It .IsAny <string >(), It .IsAny <int >())
839- .Do (() => Console .WriteLine (" Up to 3 times" ))
840- .Only (3 );
838+ .Do (() => Console .WriteLine (" Up to 3 times" )).Only (3 );
841839
842840// Executes the callback only once
841+ sut .SetupMock .Property .TotalDispensed
842+ .Throws (new Exception (" This exception is thrown only once" )).OnlyOnce ();
843+ ```
844+
845+ #### Repeat invocations (` For ` )
846+
847+ Control how many times a callback should be repeated:
848+
849+ ``` csharp
850+ sut .SetupMock .Method .Dispense (It .IsAny <string >(), It .IsAny <int >())
851+ .Do (() => Console .WriteLine (" First three times" )).For (3 )
852+ .Do (() => Console .WriteLine (" Next three times" )).For (3 );
853+
854+ sut .SetupMock .Property .TotalDispensed
855+ .Returns (10 ).For (1 )
856+ .Returns (20 ).For (2 )
857+ .Returns (30 ).For (3 );
858+ // Reads: 10, 20, 20, 30, 30, 30, 0, 0, 0, 0 …
859+ ```
860+
861+ ** Repeat ` Forever ` **
862+
863+ If you have a sequence of callbacks, you can mark the last one to repeat indefinitely using ` .Forever() ` to avoid
864+ repeating the sequence from start:
865+
866+ ``` csharp
843867sut .SetupMock .Method .Dispense (It .IsAny <string >(), It .IsAny <int >())
844- .Do (() => Console . WriteLine ( " Only once " ))
845- .OnlyOnce ();
868+ .Returns ( true ). For ( 2 ) // Returns true the first two times
869+ .Returns ( false ). Forever (); // Then always returns false
846870```
847871
848872#### Parallel callbacks
@@ -857,6 +881,9 @@ sut.SetupMock.Method.Dispense(It.IsAny<string>(), It.IsAny<int>())
857881 .Do (() => { Console .WriteLine (" Runs every other iteration" ); });
858882```
859883
884+ ** Note:**
885+ This only applies to callbacks defined via ` Do ` , not to the other setup callbacks like ` Returns ` or ` Throws ` .
886+
860887#### Invocation counter
861888
862889Access the zero-based invocation counter in callbacks:
0 commit comments