簡體   English   中英

如何使用Moq調用方法時驗證上下文條件

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

我正在使用Moq,我需要在調用mock方法時檢查一個條件。 在下面的示例中,我嘗試讀取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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM