简体   繁体   English

Moq和你传递的参数

[英]Moq and the parameters you pass

I create a MOQ object 我创建了一个MOQ对象

pass it to my class 传递给我的班级

call it and pass in an object. 调用它并传入一个对象。

How can I get access to this object to see if the right properties are set? 如何访问此对象以查看是否设置了正确的属性?

If I'm reading your question correctly you seem to have a situation like this? 如果我正确地阅读你的问题你似乎有这样的情况?

public void DoTheCalculation(ICalculator calculator) {
   calculator.Calculate(this /* Or any other object */);
}

In which case you can assert upon the arguments passed to a Mocked interface using the It.Is method that accepts a predicate: 在这种情况下,您可以使用接受谓词的It.Is方法断言传递给Mocked接口的参数:

[TestMethod]
public void DoTheCalculation_DoesWhateverItShouldDo() {
     Mock<ICalculator> calcMock = new Mock<ICalculator>();
     CalculationParameters params = new CalculationParmeters(1, 2);
     params.DoTheCalculation(calcMock.Object);

     calcMock.Verify(c => c.Calculate(It.Is<CalculationParameters>(
                         c => c.LeftHandSide == 1 
                              && c.RightHandSide == 2));

}

You use the .VerifySet() method on the mock object for this. 您可以在模拟对象上使用.VerifySet()方法。 For instance 例如

mockObject.VerifySet(o => o.Name = "NameSetInMyClass");

If it wasn't set properly, it will raise an exception. 如果设置不正确,则会引发异常。

Read more in the quick start here . 这里快速入门阅读更多内容。

Your question is kind of confusing, it's unclear what object you're referring to in the last sentence. 你的问题有点混乱,你不清楚在最后一句中你指的是什么对象。

However, every Moq wrapper has an "Object" property that is of the type that you are mocking. 但是,每个Moq包装器都有一个“Object”属性,该属性属于您正在模拟的类型。 You can access it by simply viewing that property. 您只需查看该属性即可访问它。

var myMock = new Mock<MyObj>();

var myProp = myMock.Object.MyProperty;

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

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