Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Mocking the DataSource on a GlassController<TContext, TDataSource>
[TestFixture] // using NSubstitute, NUnit and Fluent Assertions
public class GlassControllerContextItemTests
{
[Test]
public void GlassController_can_set_and_get_datasource()
{
// Arrange
ID expectedId = new ID(Guid.NewGuid());
DataSourceStubClass classToReturn = new DataSourceStubClass();
var testHarness = new DifferentTypedGlassControllerTestHarness();
testHarness.RenderingContextWrapper.HasDataSource.Returns(true);
testHarness.RenderingContextWrapper.GetDataSource().Returns(expectedId.ToString());
testHarness.SitecoreContext.GetItem<DataSourceStubClass>(expectedId.ToString()).Returns(classToReturn);
// Act
var result1 = testHarness.GlassController.DataSource;
var result2 = testHarness.GlassController.DataSource; // prove lazy loading
// Assert
result1.Should().Be(classToReturn);
result2.Should().BeSameAs(result1);
testHarness.SitecoreContext.Received(1).GetItem<DataSourceStubClass>(expectedId.ToString());
}
public class DataSourceStubClass
{
}
public class ContextStubClass
{
}
public class DifferentTypedGlassControllerTestHarness
{
public DifferentTypedGlassControllerTestHarness()
{
SitecoreContext = Substitute.For<ISitecoreContext>();
GlassHtml = Substitute.For<IGlassHtml>();
RenderingContextWrapper = Substitute.For<IRenderingContextWrapper>();
HttpContext = Substitute.For<HttpContextBase>();
GlassController = new GlassController<ContextStubClass, DataSourceStubClass>(SitecoreContext, GlassHtml, RenderingContextWrapper, HttpContext);
}
public HttpContextBase HttpContext { get; private set; }
public IRenderingContextWrapper RenderingContextWrapper { get; private set; }
public IGlassHtml GlassHtml { get; private set; }
public ISitecoreContext SitecoreContext { get; private set; }
public GlassController<ContextStubClass, DataSourceStubClass> GlassController { get; private set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.