[英]Verify that a property has been set with Moq
I'm trying to learn how to use Moq and can't get this to work: I have an interface with a TextBox and a Presenter class using that interface.我正在尝试学习如何使用 Moq 并且无法让它工作:我有一个带有 TextBox 的接口和一个使用该接口的 Presenter 类。 I want to be able to check that some method in that class has set the text property of the TextBox with a particular value.
我希望能够检查该类中的某些方法是否使用特定值设置了 TextBox 的文本属性。 This is what I've tried:
这是我尝试过的:
public interface IView { TextBox MyTextBox { get;公共接口 IView { TextBox MyTextBox { get; } }
} }
public class Presenter
{
private IView _view;
public Presenter(IView view)
{ _view = view; }
public void Foo(string txt)
{
// try to set the Text in MyTextBox:
// this gives a NullReferenceException => _view.MyTextBox.Text = txt;
}
}
In my test I want to do something like this:在我的测试中,我想做这样的事情:
[Test]
public void Test_For_TestBoxText_Set()
{
var mockView = new Mock<IView>();
var presenter = new Presenter(mockView.Object);
presenter.Foo("bar");
mockView.VerifySet(v => v.MyTextBox.Text = "bar");
}
` Can anybody point me in the right direction and also explain why this is not working? ` 谁能指出我正确的方向并解释为什么这不起作用?
You can create a real TextBox
and make the mock return it.您可以创建一个真正的
TextBox
并使模拟返回它。 Then in the assert phase, you can test against that real TextBox
.然后在断言阶段,您可以针对真正的
TextBox
进行测试。 Here is an example:下面是一个例子:
//Arrange
Mock<IView> moq = new Mock<IView>();
var textbox = new TextBox();
moq.Setup(x => x.MyTextBox).Returns(textbox);
Presenter presenter = new Presenter(moq.Object);
//Act
presenter.Foo("test");
//Assert
Assert.AreEqual("test", textbox.Text);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.