Copied to clipboard

Flag this post as spam?

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


  • Alexandre Locas 52 posts 219 karma points
    Mar 21, 2022 @ 18:31
    Alexandre Locas
    1

    The type initializer for 'Umbraco.Extensions.FriendlyPublishedContentExtensions' threw an exception

    Hi, I need to unit test the following code :

    var myPage = _publishedContentQuery.ContentAtRoot().DescendantsOrSelfOfType("myDocAlias").FirstOrDefault();
    

    When running a unit test I get the following exception :

    The type initializer for 'Umbraco.Extensions.FriendlyPublishedContentExtensions' threw an exception.'
    

    How can i refactor the code to be more testable or how can I unit test this kind of code ?

    Thank you

  • Paul Taylor 13 posts 100 karma points
    Aug 08, 2022 @ 10:26
    Paul Taylor
    1

    A good question. I hit the same issue attempting to use IPublishedContent.Url() in a unit test.

    This extension method retrieves an instance of IPublishedUrlProvider from the internal StaticServiceProvider service locator which renders the code "basically untestable", according to the documentation.

  • Emma Garland 41 posts 123 karma points MVP 7x c-trib
    Nov 23, 2022 @ 20:58
    Emma Garland
    0

    I've seen a way round the Url() issue by wrapping the .Url() method inside another method within a new, mockable class. Such as ContentExtensionsWrapper.cs, which itself has a .Url() method that calls the real method.

    e.g:

    public string Url(IPublishedContent currentPage)
    {
        return currentPage.Url();
    }
    

    Then, using Moq for example, you can pass your content item into your own mocked wrapper class, setup the expectation on the .Url() method, and return it that way:

    mockContentExtensionsWrapper.Setup(x => x.Url(It.IsAny<IPublishedContent>())).Returns("https://google.com");
    
Please Sign in or register to post replies

Write your reply to:

Draft