Sitecore FakeDB-模拟GetCurrentItem <mymodel>()

时间:2019-02-11 21:09:31

标签: unit-testing sitecore glass-mapper

我正面临一个测试我的控制器的问题单元:逻辑非常简单:控制器正在使用GetCurrentItem()函数检索上下文项,并且基于这些字段之一的值,正在调用存储库。 / p>

我的单元测试代码基于以下组合:

  • N替代
  • NUnit
  • FluentAssertions
  • FakeDb
  • GlassMapper

我尝试创建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

0 个答案:

没有答案