Copied to clipboard

Flag this post as spam?

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

  • Ismail Mayat 4511 posts 10062 karma points MVP 2x admin c-trib
    Feb 21, 2020 @ 08:52
    Ismail Mayat

    Mocking UmbracoContext in v8

    So in v7 to mock umbraco context we had anyone know how to mock umbraco context in v8?



  • Ruben Meintema 9 posts 100 karma points
    Apr 20, 2020 @ 12:13
    Ruben Meintema

    Hi Ismail,

    So there is a way to mock the UmbracoContext.

    The first question is: how do you want to use it? Say you have a function that needs an UmbracoContext, for example for resolving a product ID from the current URL. So inside your Unit Test class you would have some code like this:


    Now, how do we pass a mock of the UmbracoContext to this function, instead of a real UmbracoContext?

    First we need a HttpContext. In this article, it is explained how to use the abstract UmbracoBaseTest class, to mock the HttpContext. So let's do that, and inherit from the base class.

    In this specific case, we also need to properly set up the HttpContext with a query string:

    var request = new Mock<HttpRequestBase>();
    request.Setup(x => x.QueryString).Returns(new NameValueCollection());
    this.HttpContext.Setup(x => x.Request).Returns(request.Object);

    Then we need an UmbracoContextFactory. So we do this:

    _umbracoContextFactory = new UmbracoContextFactory(
                new UmbracoSettingsSection(),
                new UrlProviderCollection(new IUrlProvider[] { Mock.Of<IUrlProvider>() }),
                new MediaUrlProviderCollection(new IMediaUrlProvider[] { Mock.Of<IMediaUrlProvider>() }),

    And then finally we can do:

    _umbracoContext = _umbracoContextFactory.EnsureUmbracoContext(this.HttpContext.Object).UmbracoContext;

    So when we are making a UnitTest that needs an UmbracoContext, we can set it up like this:

    _umbracoContext.HttpContext.Request.QueryString["product-id"] = "123-product-mock-id";

    And then we have sufficiently prepared the umbracoContext object to pass it into the function we want to test in the first place: "myClass.GetProductId(umbracoContext);"

    I hope this helps, cheers,


Please Sign in or register to post replies

Write your reply to: