使用 Moq 调用方法时如何验证上下文条件
How to verify a contextual condition when a method is called with Moq
我正在使用 Moq,我需要在调用模拟方法时检查条件。在下面的示例中,我尝试读取 Property1 属性,但这可以是任何表达式:
var fooMock = new Mock<IFoo>();
fooMock.Setup(f => f.Method1())
.Returns(null)
.Check(f => f.Property1 == true) // Invented method
.Verifiable();
我最后的 objective 是在调用方法时检查条件是否为真。我该如何执行此操作?
您可能会使用 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);
我正在使用 Moq,我需要在调用模拟方法时检查条件。在下面的示例中,我尝试读取 Property1 属性,但这可以是任何表达式:
var fooMock = new Mock<IFoo>();
fooMock.Setup(f => f.Method1())
.Returns(null)
.Check(f => f.Property1 == true) // Invented method
.Verifiable();
我最后的 objective 是在调用方法时检查条件是否为真。我该如何执行此操作?
您可能会使用 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);