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 10092 karma points MVP 2x admin c-trib
    Feb 21, 2020 @ 08:52
    Ismail Mayat
    1

    Mocking UmbracoContext in v8

    So in v7 to mock umbraco context we had https://github.com/garydevenay/Umbraco-Context-Mock anyone know how to mock umbraco context in v8?

    Regards

    Ismail

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

    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:

    myClass.GetProductId(_umbracoContext);
    

    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(
                Mock.Of<IUmbracoContextAccessor>(),
                Mock.Of<IPublishedSnapshotService>(),
                Mock.Of<IVariationContextAccessor>(),
                Mock.Of<IDefaultCultureAccessor>(),
                new UmbracoSettingsSection(),
                Mock.Of<IGlobalSettings>(),
                new UrlProviderCollection(new IUrlProvider[] { Mock.Of<IUrlProvider>() }),
                new MediaUrlProviderCollection(new IMediaUrlProvider[] { Mock.Of<IMediaUrlProvider>() }),
                Mock.Of<IUserService>()
                );
    

    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,

    Ruben

Please Sign in or register to post replies

Write your reply to:

Draft