-6

I have the following code in a unit test where I am using Moq:

Mock<BorderedCanvas> canvas2 = new Mock<BorderedCanvas>();
canvas2.Object.Children.Add(canvas1);
canvas1.RaiseEvent(someEvent);
canvas2.Verify(c => c.RaiseEvent(It.IsAny<RoutedEventArgs>()), Times.Once);

The code fails on the second line with this message:

System.NullReferenceException : Object reference not set to an instance of an object.

Any idea why I can not access the underlying object of the mock canvas2?

octavian
  • 15,986
  • 38
  • 119
  • 229
  • 2
    `Children` is null – Camilo Terevinto Mar 01 '18 at 13:50
  • Reference [Moq Quickstart](https://github.com/Moq/moq4/wiki/Quickstart) to understand how to use the framework and why you get null. – Nkosi Mar 01 '18 at 13:50
  • This appears to be an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). What is the ultimate goal you are trying to achieve? – Nkosi Mar 01 '18 at 13:51
  • Why is `Children` null? If you instantiate a `new BorderedCanvas()`, its `Children` field will not be null. – octavian Mar 01 '18 at 13:59
  • 2
    Then why are you using a mock to begin with? just create an instance and use that. If `Children` is virtual, moq will override it and return null by default unless you tell it otherwise. – Nkosi Mar 01 '18 at 14:01
  • As it is shown in the last line of my code, I am using a mock because I want to check if one of the methods of the underlying object is called. – octavian Mar 01 '18 at 14:03
  • 2
    mocks should be used to mock dependencies of the subject under test, not to mock the subject of the test. – Nkosi Mar 01 '18 at 14:04
  • `canvas2` is not the subject under test. `canvas1` is – octavian Mar 01 '18 at 14:06
  • Check this https://github.com/Moq/moq4/wiki/Quickstart#properties and see if it helps. specifically `mock.SetupAllProperties();` – Nkosi Mar 01 '18 at 14:15

1 Answers1

1

Everything about the mock object will return default values unless you have told it to behave otherwise. Since you haven't told it how the Children property should behave, it is returning the default value for that type, which is null. Hence the NullReferenceException when you try to call "Add" on a null object. (Wow, beaten to it by multiple comments, above...)

Richardissimo
  • 5,083
  • 2
  • 12
  • 32