Search code examples
c#unit-testingpropertiestextboxmoq

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. 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. This is what I've tried:

public interface 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?


Solution

  • You can create a real TextBox and make the mock return it. Then in the assert phase, you can test against that real 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);