3

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?

fatihyildizhan
  • 8,614
  • 7
  • 64
  • 88
wosi
  • 373
  • 4
  • 15

1 Answers1

1

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);
Yacoub Massad
  • 27,509
  • 2
  • 36
  • 62
  • I've tried your solution: it works! I've tested it a bit further by changing the property type to string and then also the SetupSet/VerifySet worked. So it seems that the property SetupSet only works with primitive types and not with reference types, is that correct? Thanks a lot. – wosi Mar 29 '16 at 14:30
  • I am not sure I understand. What didn't work? Which property you changed to string? – Yacoub Massad Mar 29 '16 at 14:32
  • You misunderstood: everything worked. I only investigated a little further by changing the type of the property declared in the interface from TextBox to string. Then I could also use SetupSet without any error. So apparently that NullReferenceException I've experienced only gets thrown when you use a reference type (e.g. like TextBox), right ? – wosi Mar 29 '16 at 15:16
  • It seems that Moq does not auto-mock return values of properties and methods of mocked interfaces. I am not sure if and how this behavior can be changed. – Yacoub Massad Mar 31 '16 at 21:30