简体   繁体   English

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

[英]How to verify a contextual condition when a method is called with Moq

I'm using Moq and I need to check a condition when a mock method is called. 我正在使用Moq,我需要在调用mock方法时检查一个条件。 Into following example i try to read the Property1 property, but this could be any expression: 在下面的示例中,我尝试读取Property1属性,但这可以是任何表达式:

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

My final objective is to check if a condition is true when the method is called. 我的最终目标是在调用方法时检查条件是否为真。 How can I perform this? 我怎么能这样做?

You could probably use Callback() , example: 您可以使用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"));

In your case something like: 在你的情况下像:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM