這是基於Moq QuickStart示例在每次調用時返回不同值的一種方法。
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());
如果該方法返回void,用途:
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)
{
// Would really want to call Assert.Throws instead of try..catch.
Console.WriteLine("Got exception");
}
myMock.Object.Execute();
Console.WriteLine("OK!");
這看起來很有趣,但是,如果該方法是無效的,並且在安裝後沒有得到「返回」方法呢?實際上,如果「GetCountThing」返回一個int,它就會工作,如果它返回其他東西,它將不會編譯。 –
@SergioRomero - 請參閱編輯答案。 – TrueWill
至於如果它不是一個int,請改變你從'Returns'行返回的內容。它不一定是'calls'的價值。 – TrueWill