gpt4 book ai didi

c# - 使用 Moq 调用方法时如何验证上下文条件

转载 作者:行者123 更新时间:2023-11-30 15:24:58 25 4
gpt4 key购买 nike

我正在使用 Moq,我需要在调用模拟方法时检查条件。在下面的示例中,我尝试读取 Property1 属性,但这可以是任何表达式:

var fooMock = new Mock<IFoo>();
fooMock.Setup(f => f.Method1())
.Returns(null)
.Check(f => f.Property1 == true) // Invented method
.Verifiable();

我的最终目标是在调用方法时检查条件是否为真。我该如何执行此操作?

最佳答案

您可能会使用Callback(),例如:

// callbacks can be specified before and after invocation
mock.Setup(foo => foo.Execute("ping"))
.Callback(() => Console.WriteLine("Before returns"))
.Returns(true)
.Callback(() => Console.WriteLine("After returns"));

在你的情况下是这样的:

bool isProperty1True = false;
var fooMock = new Mock<IFoo>();
fooMock.Setup(f => f.Method1())
.Callback(() => isProperty1True = fooMock.Object.Property1 == true)
.Returns(null)
.Verifiable();

Assert.IsTrue(isProperty1True);

关于c# - 使用 Moq 调用方法时如何验证上下文条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31918497/

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