Mocking Property Values in Umbraco 9 (and Umbraco 8)

So I just got back from my summer vacation and I thought I would kickstart this blogging thing with a short and straight-forward blogpost that's easy to digest for anyone (like me) coming back from a long break from coding.

Mocking property values
Mocking published content property values is probably the most common kind of mocking used when building websites in Umbraco.

We mock returned property values for some sort of content and then in our test we want to make sure that a certain viewmodel gets mapped against the property values we expected.

And although this kind of mocking can be done in just a few lines of code (5 to be exact) I’ve created an extension method that makes these kind of tests both shorter and more readable.

Note: This works for both Umbraco v8 and v9. This examples uses Moq but it can just as easily be converted to let’s say NSubstitute.

This creates a mock of IPublishedProperty and setup the return values for the Alias property as well as the GetValue and HasValue methods and then applies this property mock to the IPublishedContent item.

Note that the value is of type object, so it will work regardless if you want to mock a property value of a simple string or an integer but also complex types like a another IPublishedContent or a list of BlockList items. It's totally up to you!

Using this extension method in my tests I can now go:

This not only reduces 5 lines of code in every single test where I’m mocking property values (which is most of them I guess) but I also think it makes it cleaner and really easy to follow along.

That's a wrap!
I told you it was going to be short and to the point didn't I? Hope you enjoyed it and that it can help someone, somewhere in the future.

Cheers friends! ❤️