我正面临一个测试我的控制器的问题单元:逻辑非常简单:控制器正在使用GetCurrentItem()函数检索上下文项,并且基于这些字段之一的值,正在调用存储库。 / p>
我的单元测试代码基于以下组合:
我尝试创建ISitecoreContext
的替代品并使用了using(RenderingContext.EnterContext(new Rendering(), myItem))
,但是当我的控制器命中GetCurrentItem()
时,测试不断抛出null引用异常。如果我检查代码,则Sitecore.Context.Item
也会显示为空。
如果我使用Sitecore.Data.DatabaseSwitcher
,我可以看到Sitecore.Context.Item
已填充,但是Glass仍然无法执行获取当前项目的操作。
您能帮助我了解我在做什么错吗?这是我的代码:
public void ListWithFiltersShouldReturnPartialWithSeoItemAttributes(Db db, string itemName, ID itemId, string filterChanged)
{
//Arrange
var repositorySubstitute = Substitute.For<IProductRepository>();
var seoDataRepository = Substitute.For<ISeoDataRepository>();
var item = new DbItem(itemName, itemId, new ID(Constants.ProductListingPageTemplate))
{{ ProductListingPageConstants.UseSEOItemCopyFieldName, "true" }};
db.Add(item);
SetupSeoItem(seoDataRepository, item);
var contextItem = db.GetItem(itemId);
using (var controller = new TestableProductController(repositorySubstitute, seoDataRepository))
{
var context = new RenderingContext { Rendering = new Rendering { Item = contextItem } };
ContextService.Get().Push(context);
SearchSetting searchSetting = new SearchSetting() { SortBy = "A-Z" };
if (db != null)
{
repositorySubstitute.GetProductListWithFilters(db.GetItem(item.ID), searchSetting).ReturnsForAnyArgs(new ProductListModel() { SearchSetting = searchSetting });
}
var contextMock = Substitute.For<HttpContextBase>();
var requestMock = Substitute.For<HttpRequestBase>();
var queryString = new NameValueCollection();
queryString["foo"] = "bar";
requestMock.QueryString.Returns(queryString);
contextMock.Request.Returns(requestMock);
controller.ControllerContext = new ControllerContext(contextMock, new RouteData(), controller);
//Act - This breaks. The ListWithFilters function calls the Glass GetContextItem()
ActionResult plp = controller.ListWithFilters(searchSetting,filterChanged);
//Assert
plp.Should().BeOfType<PartialViewResult>();
}
}
非常感谢!
A