Slides from CG16 and testing IPublishedContent properties

CodeGarden 2016 is over, and I had the best time since last CG. Thanks everyone for a great time, old friends and new friends.
The slides from my presentation is available here. The presentation is also available for streaming here.

Several people asked me how to stub up GetPropertyValue<T>(), so here's a bonus test for y'all.

The gist of it is that GetPropertyValue<T> calls GetProperty, which is a method on the IPublishedContent interface.
This is good news, you can just stub that one per property alias. Also, GetPropertyValue<T> checks whether the value is already of the given type. This means that you can just stub is as the type you are getting it as, and hence skip setting up any IPropertyValueConverter.

This test is also available on the git repo accompanying the presentation. (Which also now has a compatible version of Umbraco.Tests. Sorry. :) )

[TestFixture]
public class Stubbing_Published_Properties
{
    [Test]
    public void For_GetPropertyValueOfType()
    {
        var contentStub = new Mock<IPublishedContent>();
        var propertyStub = new Mock<IPublishedProperty>();

        propertyStub.Setup(p => p.Value).Returns(new ValueType("a text", 15));

        // GetPropertyValue<T> calls GetProperty and checks whether source is of T, so just skip converters.
        contentStub.Setup(c => c.GetProperty("test", false)).Returns(propertyStub.Object);

        var content = contentStub.Object;
        var propertyValue = content.GetPropertyValue<ValueType>("test");

        Assert.AreEqual("a text", propertyValue.Text);
        Assert.AreEqual(15, propertyValue.Number);
    }
}

public class ValueType
{
    public string Text { get; set; }
    public int Number { get; set; }

    public ValueType(string text, int number)
    {
        Text = text;
        Number = number;
    }
}

[Edit march 2017] Umbraco.Tests is now on Nuget, and I now recommend extracting Umbraco support into its own class. See The basic of unit testing Umbraco just got simpler.

Author

comments powered by Disqus