gpt4 book ai didi

c# - 如何使模拟第一次抛出异常并在第二次返回值

转载 作者:太空狗 更新时间:2023-10-29 19:58:46 25 4
gpt4 key购买 nike

我使用 Moq 作为我的模拟框架,我需要测试一个类,当特定类型的异常运行时,它会继续尝试,直到情况得到解决,一旦发生,执行完成。

所以我需要的是类似于:

myMock = Mock<IFoo>();

myMock.Setup(m => m.Excecute()).Throws<SpecificException>();
myMock.Setup(m => m.Execute());

var classUnderTest = MyClass(myMock);
classUnderTest.DoSomething();

Assert.AreEqual(expected, classUnderTest.Result);

感谢您提供的任何帮助。

最佳答案

这是一种方式,基于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!");

关于c# - 如何使模拟第一次抛出异常并在第二次返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7919886/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com