Copied to clipboard

Flag this post as spam?

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

  • Rasmus Olofsson 23 posts 187 karma points c-trib
    Oct 19, 2020 @ 13:05
    Rasmus Olofsson

    How to unit test with the new .Url() extension method? Throws exception and can't mock it

    The old .Url property on IPublishedContent is marked as obsolete and will dissapear. It has been replaced by an extension method in Umbraco.Web namespace.

    The old .Url property was easy to mock: content.Setup(x => x.Url).Returns(url);

    Now it doesn't work to mock the Setup of the property because it is an extension method and they can't be mocked. Using a wrapper around the extension method doesn't work either.

    If I skip setting up the extension method then my unit tests will throw a null reference exception because the UmbracoMapper lib from Andy Butland requires the Url() to be set.

    Any advice?

  • Dennis Adolfi 1075 posts 6436 karma points MVP 4x c-trib
    Feb 02, 2021 @ 05:53
    Dennis Adolfi

    Hi Rasmus.

    See conversation on twitter:

    To summarize:

    1. .Url() extension is not testable since it uses a static service locator without a setter so it can´t be mocked (Current.Factory).
    2. .Url has been deprecated so you can still use it but be aware in the netcore version it’s going away. It will not go away in v8 but you would have to change it if you updgrade/rebuild to v9.
    3. In Netcore version .Url() will be testable since dotnetcore has the option of passing in its dependencies which makes it easier to test.
  • Alexandre Locas 52 posts 217 karma points
    Mar 21, 2022 @ 18:07
    Alexandre Locas


    If currently .Url() can't be mocked, what is the alternative to get the Url and be able to unit test the code ?

    Thank you

  • Alex Ellis-Wilson 1 post 71 karma points
    Oct 24, 2022 @ 16:33
    Alex Ellis-Wilson

    Hey Alexandre,

    I had this same problem a while back when first writing Xunit tests for a project I was working on and I found that you can use the .Url method without brackets instead, and mock that instead of the .Url() method. However, you should be careful when changing the methods over to ensure the data is still being recieved properly.

Please Sign in or register to post replies

Write your reply to: