Setup
A setup decides how a member of the mock behaves when it is called: what it returns, whether it throws, and which
callbacks run. All setups start at dispenser.Mock.Setup and mirror the members of the mocked type:
| Member kind | Example |
|---|---|
| Methods | dispenser.Mock.Setup.Dispense("Dark", It.IsAny<int>()).Returns(true); |
| Properties | dispenser.Mock.Setup.TotalDispensed.InitializeWith(42); |
| Indexers | dispenser.Mock.Setup["Dark"].Returns(10); |
| Events | dispenser.Mock.Raise.ChocolateDispensed("Dark", 3); |
Building blocks
All member kinds share the same vocabulary:
Returns(…)/Throws(…)decide the result. Called several times, they form a sequence that starts over after the last entry.Do(…)runs a callback. For properties and indexers, useOnGet.Do(…)andOnSet.Do(…).InitializeWith(…)gives properties and indexers a start value, after which they behave like normal storage.- Values and matchers such as
It.IsAny<int>()decide which calls a setup applies to. See Parameter matching. - Modifiers such as
.For(n),.Only(n),.When(…)and.Forever()control how often an entry applies. See Advanced callback features.
Chain what belongs together
When several setups match a call, the one defined last wins. Every dispenser.Mock.Setup.X statement starts a new
setup, so chain everything that belongs to one setup instead of repeating the statement:
dispenser.Mock.Setup.TotalDispensed
.InitializeWith(42)
.OnSet.Do(newValue => Console.WriteLine(newValue));
Members without a setup fall back to the mock's MockBehavior:
methods return default values, and properties and indexers store the values written to them. You can also pass the
setups directly to CreateMock.