TIL... How to mock Property Getters in XUnit

2019-11-13

So Friday, I was working with a colleague trying to setup unit tests, in XUnit for an existing class. He had called me over to see if we could figure out how to mock an odd Interface. The Interface specified a Property with a getter. And we had started by trying to replace the property itself on the Object instantiation of the mock. However, the compiler was complaining about it, so we puzzled for a bit.

It was about that time that I remembered that Properties were just syntactic sugar. And that Getters really are just functions. With those words in mind, I was able to find a resource almost immediately which explained 'how to Mock Property Getters in XUnit'. Thank you StackOverflow!

Turns out to be wicked simple:

1
2
3
mockedThing
.SetupGet(x=> x.PropertyToMock)
.Returns(mockPropertyValue);

That's it! And that's how I learned how to Mock Property Getters in XUnit.