Last active
August 17, 2019 15:57
-
-
Save takahirohonda/ad414420ffb5dd8208d69b657b8cd6c0 to your computer and use it in GitHub Desktop.
how-to-mock-rendering-parameters-in-unit-test-sitecore-1.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using FluentAssertions; | |
using NSubstitute; | |
using Sitecore.Mvc.Presentation; | |
using SitecoreDev.Feature.Design.Controllers; | |
using SitecoreDev.Feature.Design.Models; | |
using SitecoreDev.Feature.Design.Repository; | |
using System; | |
using System.Collections.Generic; | |
using System.Web.Mvc; | |
using Xunit; | |
namespace SitecoreDev.Feature.Design.Tests | |
{ | |
public class CustomDataDivControllerTests | |
{ | |
private readonly ICustomDataDivRepository repository; | |
public CustomDataDivControllerTests() | |
{ | |
this.repository = Substitute.For<ICustomDataDivRepository>(); | |
} | |
[Fact] | |
public void CustomDataDivController_Should_Return_View_With_Correct_Model() | |
{ | |
// Arrange | |
// (1) Set rendering parameter | |
var rendering = new Rendering(); | |
// Parameters are publicly accessible field in rendering. | |
// RenderingParameters takes query string as the constructor argument. | |
rendering.Parameters = new RenderingParameters("hey=hello&more=moreValues"); | |
// (2) Create expected model | |
var expectedModel = new CustomDataDiv() | |
{ | |
CustomData = new Dictionary<string, string> | |
{ | |
{ "hey", "hello" }, | |
{ "more", "moreValues" } | |
} | |
}; | |
// (3) Stub the repository function | |
repository.GetParamsForCustomDiv(rendering.Parameters).Returns(expectedModel); | |
// (4) Create rendering context with the mocked rendering | |
using (RenderingContext.EnterContext(rendering)) | |
{ | |
var controller = new CustomDataDivController(this.repository); | |
// Act | |
ViewResult result = controller.CustomDataDiv() as ViewResult; | |
var actualViewName = result.ViewName; | |
var actualModel = result.ViewData.Model as CustomDataDiv; | |
// Assert | |
Assert.NotNull(result); | |
result.ViewName.Should().Be(String.Empty); | |
actualModel.Should().BeEquivalentTo(expectedModel); | |
} | |
} | |
[Fact] | |
public void CustomDataDivController_Should_Return_No_Model_Without_Parameters() | |
{ | |
// Arrange | |
using (RenderingContext.EnterContext(new Rendering())) | |
{ | |
var controller = new CustomDataDivController(this.repository); | |
// Act | |
ViewResult result = controller.CustomDataDiv() as ViewResult; | |
var actualModel = result.ViewData; | |
// Assert | |
Assert.NotNull(result); | |
actualModel.Should().HaveCount(0); | |
} | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment