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 we have sufficiently prepared the umbracoContext object to pass it into the function we want to test in the first place: "myClass.GetProductId(umbracoContext);"
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
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:
Then we need an UmbracoContextFactory. So we do this:
And then finally we can do:
So when we are making a UnitTest that needs an UmbracoContext, we can set it up like this:
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
is working on a reply...