I have some code that retrieves a glass item like this:
var root = this.RequestContext.SitecoreService.GetItem<ILookupFolderTemplate>(
new GetItemByIdOptions(new Guid("{DB4B5F35-E3BA-416A-842D-3D25B9C10A23}")));
So, using IRequestContext
I call the instance of SitecoreService
, I request an item using GetItemByIdOptions
. This is giving me a problem when I try to mock it for a unit test.
So, for my test (using NSubstitute
) I mock the whole process like this:
[Fact]
public void GetItem_RequestContextGetItemOptions_ReturnsCorrectItem()
{
var idGuid = Guid.NewGuid();
var product = Substitute.For<ISitecoreItem>();
product.Name = "Hello world";
product.ID = new ID(idGuid);
var context = Substitute.For<IRequestContext>();
var service = Substitute.For<ISitecoreService>();
context.SitecoreService.Returns(service);
context.SitecoreService.GetItem<ISitecoreItem>(new GetItemByIdOptions(idGuid)).Returns(product);
var result = context.SitecoreService.GetItem<ISitecoreItem>(new GetItemByIdOptions(idGuid));
result.Should().NotBeNull();
result.Name.Should().Be("Hello world");
result.ID.ToGuid().Should().Be(idGuid);
}
And this test fails because result.Name
is empty.
BUT, if I create the GetItemByIdOptions
separately, like this, it passes:
[Fact]
public void GetItem_RequestContextGetItemOptions_ReturnsCorrectItem()
{
var idGuid = Guid.NewGuid();
var product = Substitute.For<ISitecoreItem>();
product.Name = "Hello world";
product.ID = new ID(idGuid);
var context = Substitute.For<IRequestContext>();
var service = Substitute.For<ISitecoreService>();
context.SitecoreService.Returns(service);
var options = new GetItemByIdOptions(idGuid);
context.SitecoreService.GetItem<ISitecoreItem>(options).Returns(product);
var result = context.SitecoreService.GetItem<ISitecoreItem>(options);
result.Should().NotBeNull();
result.Name.Should().Be("Hello world");
result.ID.ToGuid().Should().Be(idGuid);
}
Which is all well and good in the context of this test. But when I go and test actual code, I'm not pulling that options out of the GetItem
method, I'm instantiating it inside the GetItem
statement, so my test fails. It seems like new-ing the options up is the problem. How can I mock this sort of method?