I am trying to Unit Test precompiled Views, generated by RazorGenerator, that inherit from GlassView, based on this article: http://blog.davidebbo.com/2011/06/unit-test-your-mvc-views-using-razor.html.

I have created a model using the answer from: https://stackoverflow.com/questions/24658121/issue-unit-testing-sitecore-and-glass-with-nunit

// Instantiate the view directly. 
var view = new _Views_Components_QuickAction_cshtml();

//Instantiate a TDS Code Generated Glass Model
var model =  new QuickActionDatasource()
     Icon= new IconAnimated(),
     Link = new Link()
         Text = "Link Text"

 // Build a Glass model to pass to View - this works if you're intention is to test the model
 ISitecoreService service = Substitute.For<ISitecoreService>();
 var result = service.GetItem<QuickActionDatasource>(Guid.Empty);

//Use Razor
HtmlDocument doc = view.RenderAsHtml(result);

// Use the HtmlAgilityPack object model to verify the view.
HtmlNode node = doc.DocumentNode.Element(".quickaction");

Currently this fails on GlassView in the InitHelpers method, on the call:


Specific error:

throw new NotSupportedException("Sitecore Context Requires a Glass Context");

When it can't create a Context object from the GlassContextProvider.

What would be the best way to have the IntiHelper method initialize NSubstitute objects (i.e. an ISitecoreContextFactory), so that I can fake rendering? Can I substitute a GlassContext to pass through the MVC View rendering process?

Having the Views precompiled highlights Code Generation issues thrown at runtime. The Views are rendered via a Sitecore ViewRenderings, and are essentailly 'dumb' Presentation components with a datasource.

1 Answer 1


I would mock ISitecoreContextFactory and the return a mocked ISitecoreContext and see if this solves your problem. You might have further issues if you are using Glass HtmlHelpers.

TBH I am not sure how easy unit testing the views will be with Glass since this is something we never considered being a requirement.

You can set the default static for the SitecoreContextFactory https://github.com/mikeedwards83/Glass.Mapper/blob/master/Source/Glass.Mapper.Sc/IoC/SitecoreContextFactory.cs#L12

  • InitHelpers initializes SitecoreContextFactory via Default prop: this.SitecoreContext = SitecoreContextFactory.Default.GetSitecoreContext(); How could I inject an ISitecoreContextFactory in there? Can't think of a way using Reflection...? Any other injection points?
    – Ryan Tuck
    Commented Jan 9, 2017 at 10:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.