单元测试渲染上下文。页面上下文抛出异常

Unit testing rendering context. Page context throws an exception

我正在尝试使用 sitecoreFakeDB 创建单元测试,我的代码显示如下:

using (Sitecore.FakeDb.Db db = new Sitecore.FakeDb.Db() { new Sitecore.FakeDb.DbItem("source") })
        {
            var contextItem = db.GetItem("/sitecore/content/source");
            var args = new Sitecore.Pipelines.PipelineArgs();
            using (RenderingContext.EnterContext(new Rendering(), contextItem))
            {

                var processor = new Mock<Sitecore.FakeDb.Pipelines.IPipelineProcessor>();

                db.PipelineWatcher.Register("mypipeline", processor.Object);

                Sitecore.Pipelines.CorePipeline.Run("mypipeline", args);

                Xunit.Assert.NotNull(args.Current));
            }
        }

检查 RenderingContext.Current 中的 pagecontext 时抛出异常。如何获得 pagecontext 的值?

好像没有PageContext.EnterContext类似进入渲染上下文的方法。您可以通过 ContextService static class 手动设置它(但如果您不能正确清理它,请注意可能的垃圾):

ContextService.Get().Push(new PageContext());
var currentContext = RenderingContext.Current;
Assert.NotNull(currentContext.PageContext); // pass