Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking RenderingContext using Sitecore.FakeDB

I'm using Sitecore.FakeDB to write unittests for my Sitecore. I would like to mock the RenderingContext, to set the Rendering Parameters or Datasource of my current item.

However, when calling RenderingContext.Current, my unittest crashes with the following error:

Test method YourAssembly.YourClass.YourTest threw exception: 
System.InvalidOperationException: Attempt to retrieve context object of type 'Sitecore.Mvc.Presentation.RenderingContext' from empty stack.

Is mocking the RenderingContext supported by Sitecore.FakeDB?

If this is not supported, I'll abstract calls to RenderingContext away from my code using Marc Duiker's blog

like image 742
Rogier van het Schip Avatar asked May 19 '26 07:05

Rogier van het Schip


1 Answers

How about use RenderingContext.EnterContext. Something like this:

Item datasourceContextItem = db.GetItem("/sitecore/content/some/stuff");

using (RenderingContext.EnterContext(new Rendering(), datasourceContextItem))
{

    IMyViewModelRepository repository = new MyViewModelRepository();
    MyController controller = new MyController(repository);

    ViewResult view = (ViewResult)controller.Index();

    ((MyViewModel)view.Model).MyHtmlStringProperty.ToString().Should().Be("some value");
}
like image 83
gorhal Avatar answered May 22 '26 10:05

gorhal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!