This is one way, based on the Moq QuickStart example, to return different values ββfor each call.
var mock = new Mock<IFoo>(); var calls = 0; mock.Setup(foo => foo.GetCountThing()) .Returns(() => calls) .Callback(() => { calls++; if (calls == 1) { throw new InvalidOperationException("foo"); } }); try { Console.WriteLine(mock.Object.GetCountThing()); } catch (InvalidOperationException) { Console.WriteLine("Got exception"); } Console.WriteLine(mock.Object.GetCountThing());
If the method returns void, use:
var myMock = new Mock<IFoo>(); bool firstTimeExecuteCalled = true; myMock.Setup(m => m.Execute()) .Callback(() => { if (firstTimeExecuteCalled) { firstTimeExecuteCalled = false; throw new SpecificException(); } }); try { myMock.Object.Execute(); } catch (SpecificException) {
Truewill
source share