Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Martin Höijer 1 post 71 karma points
    Nov 14, 2019 @ 12:09
    Martin Höijer
    0

    Mocking Nested Content in unit tests

    Hi everyone,

    I am using nested content frequently in my solution and I fail a bit when I try to unit test them.

    I fetch the nested content with this line of code

    var elements = pageContent.Value("nestedContentAlias", defaultValue: Enumerable.Empty<IPublishedElement>());
    

    And this works fine when the site is run. But how do I mock this? I've tried alot of different approaches for this. At first, when the test was run, Umbraco threw error when above line was run.

    System.InvalidCastException HResult=0x80004002 Message=Unable to cast object of type 'System.Collections.Generic.List`1[Umbraco.Core.Models.PublishedContent.IPublishedElement]' to type 'Umbraco.Core.Models.PublishedContent.IPublishedValueFallback'. Source=Umbraco.Core StackTrace: at Umbraco.Core.FactoryExtensions.GetInstance[T](IFactory factory) at Umbraco.Core.Composing.Current.getPublishedValueFallback() at Umbraco.Web.Composing.Current.getPublishedValueFallback()

    I managed to bypass this by doing this in the test setup (row 2):

    factory = Substitute.For<IFactory>();
    factory.GetInstance(typeof(IPublishedValueFallback)).Returns(Substitute.For<IPublishedValueFallback>());
    Current.Factory = factory;
    

    I now get items as IEnumerable

    var elements = pageContent.Value("nestedContentAlias", defaultValue: Enumerable.Empty<IPublishedElement>()); 
    foreach(var element in elements)
    {
        var stringValue = element.Value<string>("stringAlias");
    }
    

    but stringValue above is always null.

    Can someone give examples on how I can mock a nested content where the IPublishedElement contains mocked properties?

    Kind regards, Martin

Please Sign in or register to post replies

Write your reply to:

Draft