### Create Mock Site Contexts with SiteInfoPropertiesBuilder Source: https://context7.com/smarchenko/sitecoredi.nsubstitute.helper/llms.txt Use SiteInfoPropertiesBuilder to fluently define site properties and implicitly convert them to SiteContext, SiteInfo, or Site objects. ```csharp using Sitecore.NSubstituteUtils; using Sitecore.Sites; using Sitecore.Web; // Create a basic site context SiteContext basicSite = new SiteInfoPropertiesBuilder("MySite") .WithHostName("www.mysite.com") .WithDatabase("web") .WithStartItem("/home"); string startItem = basicSite.StartItem; // Returns "/home" // Create a fully configured site var siteBuilder = new SiteInfoPropertiesBuilder("CorporateSite") .WithHostName("corporate.example.com") .WithTargetHostName("corporate.example.com") .WithDatabase("web") .WithRootPath("/sitecore/content/Corporate") .WithStartItem("/home") .WithLanguage("en") .WithDomain("extranet") .WithVirtualFolder("/") .WithPhysicalFolder("/") .WithAllowDebug(false) .WithEnablePreview(true) .WithEnableWebEdit(true) .WithEnableDebugger(false) .WithCacheHtml(true) .WithHtmlCacheSize("50MB") .WithRegistryCacheSize("5MB") .WithViewStateCacheSize("10MB") .WithFilteredItemsCacheSize("10MB") .WithDisableBrowserCaching(false) .WithDisableClientData(false) .WithLanguageEmbedding(true) .WithRequireLogin(false) .WithLoginPage("/login"); // Convert to different Sitecore site types SiteContext siteContext = siteBuilder; // Implicit conversion to SiteContext SiteInfo siteInfo = siteBuilder; // Implicit conversion to SiteInfo Site site = siteBuilder; // Implicit conversion to Site // Access site properties string hostName = siteContext.HostName; // Returns "corporate.example.com" string language = siteContext.Language; // Returns "en" string database = siteContext.Database?.Name; // Get raw site properties dictionary var properties = siteBuilder.ToSitecoreSiteInfoProperties(); string siteName = properties["name"]; // Returns "CorporateSite" ``` -------------------------------- ### Create SiteContext with SiteInfoPropertiesBuilder Source: https://github.com/smarchenko/sitecoredi.nsubstitute.helper/blob/master/README.md Build site properties fluently and cast them to Sitecore types like SiteContext. ```C# [Test] public void CreatingSiteContext_ShouldBeTrivial() { SiteContext siteContext = new SiteInfoPropertiesBuilder("TestSiteName") .WithHostName("test-site-host") .WithDatabase("test-database") .WithStartItem("/test/start/items"); siteContext.StartItem.Should().Be("/test/start/items"); } ``` -------------------------------- ### Mock Sitecore Components with FakeUtil Source: https://context7.com/smarchenko/sitecoredi.nsubstitute.helper/llms.txt FakeUtil provides static methods to instantiate mock databases, items, fields, and URIs for unit testing scenarios. ```csharp using NSubstitute; using Sitecore.Data; using Sitecore.Data.Items; using Sitecore.Data.Fields; using Sitecore.Globalization; using Sitecore.NSubstituteUtils; // Create fake database Database fakeDb = FakeUtil.FakeDatabase("master"); string dbName = fakeDb.Name; // Returns "master" Database defaultDb = FakeUtil.FakeDatabase(); // Uses "fakeDB" as default name // Create fake items with various configurations Item basicItem = FakeUtil.FakeItem(); Item namedItem = FakeUtil.FakeItem("ProductItem"); Item itemWithDb = FakeUtil.FakeItem("ProductItem", fakeDb); Item fullItem = FakeUtil.FakeItem(ID.NewID, "ProductItem", fakeDb); // Set up item properties FakeUtil.FakeItemFields(basicItem); // Initialize field collection FakeUtil.FakeItemPath(basicItem); // Initialize Paths property FakeUtil.FakeItemAccess(basicItem); // Initialize Access property FakeUtil.FakeItemAppearance(basicItem); // Initialize Appearance property FakeUtil.FakeItemStatistics(basicItem); // Initialize Statistics property FakeUtil.FakeItemTemplate(basicItem); // Initialize Template property FakeUtil.FakeItemLanguage(basicItem); // Initialize Language property FakeUtil.FakeItemLinks(basicItem); // Initialize Links property FakeUtil.FakeItemLocking(basicItem); // Initialize Locking property FakeUtil.FakeItemVersions(basicItem); // Initialize Versions property FakeUtil.FakeItemAxes(basicItem); // Initialize Axes property FakeUtil.FakeItemEditing(basicItem); // Initialize Editing property FakeUtil.FakeItemUri(basicItem); // Initialize Uri property // Create and configure fake fields Field fakeField = FakeUtil.FakeField(ID.NewID, basicItem); FakeUtil.FakeFieldValue("FieldName", "FieldValue", basicItem); FakeUtil.FakeFieldValue(ID.NewID, "FieldName", "FieldValue", basicItem); // Create fake URIs ItemUri itemUri = FakeUtil.FakeItemUri(); ItemUri customUri = FakeUtil.FakeItemUri( ID.NewID, "/sitecore/content/home", Language.Parse("en"), Sitecore.Data.Version.Latest, "master" ); DataUri dataUri = FakeUtil.FakeDataUri(); DataUri customDataUri = FakeUtil.FakeDataUri( ID.NewID, Language.Invariant, Sitecore.Data.Version.Latest ); ``` -------------------------------- ### Create Fake Items with FakeUtil Source: https://github.com/smarchenko/sitecoredi.nsubstitute.helper/blob/master/README.md Use FakeUtil for simple creation of mocked Sitecore objects, though FakeItem is recommended for more complex scenarios. ```C# [Test] public void FakeItem_ShouldReturn_FakeItemWithSpecifiedParameters() { var database = FakeUtil.FakeDatabase(); var id = ID.NewID; var name = "test item name"; var item = FakeUtil.FakeItem(id, name, database); item.Should().NotBeNull(); item.ID.Should().Be(id); item.Name.Should().Be(name); item.Database.Should().Be(database); } ``` -------------------------------- ### Create Item Structures with FakeItem Source: https://github.com/smarchenko/sitecoredi.nsubstitute.helper/blob/master/README.md Use FakeItem to initialize items with properties and define parent-child hierarchies in a fluent manner. ```C# [Test] public void FakeItem_ShouldSimplify_StructureCreation() { var item = new FakeItem(); var parentID = ID.NewID; var childID1 = ID.NewID; var childID2 = ID.NewID; var scItem = (Item)item; // create fake item with specified parent and 2 children item .WithParent(new FakeItem(parentID)) .WithChild(new FakeItem(childID1, scItem.Database)) .WithChild(new FakeItem(childID2, scItem.Database)); scItem.ParentID.Should().Be(parentID); scItem.Parent.ID.Should().Be(parentID); scItem.Children.Count.Should().Be(2); scItem.Database.GetItem(childID1).Should().NotBeNull(); scItem.Database.GetItem(childID1).ID.Should().Be(childID1); } ``` -------------------------------- ### Define and Use Custom FakeItem Extensions Source: https://context7.com/smarchenko/sitecoredi.nsubstitute.helper/llms.txt Create custom extension methods to configure FakeItem behavior and use them in unit tests to build complex mock objects. ```csharp using Sitecore.Data.Items; using Sitecore.NSubstituteUtils; using NSubstitute; // Define custom extension methods public static class CustomFakeItemExtensions { public static FakeItem WithItemHelp(this FakeItem item, ItemHelp itemHelp) { item.ToSitecoreItem().Help.Returns(itemHelp); return item; } public static FakeItem WithCustomProperty(this FakeItem item, string propertyValue) { // Configure custom item behavior var scItem = item.ToSitecoreItem(); scItem["CustomProperty"].Returns(propertyValue); return item; } public static FakeItem AsProductItem(this FakeItem item, string productName, decimal price) { return item .WithTemplate(ProductTemplateId) .WithField("ProductName", productName) .WithField("Price", price.ToString()) .WithField("InStock", "1"); } private static readonly ID ProductTemplateId = ID.Parse("{PRODUCT-TEMPLATE-ID}"); } // Usage of custom extensions [Test] public void TestWithCustomExtensions() { var productItem = new FakeItem() .WithName("Widget") .AsProductItem("Premium Widget", 99.99m) .WithCustomProperty("custom value"); Item item = productItem; string productName = item["ProductName"]; // Returns "Premium Widget" string customProp = item["CustomProperty"]; // Returns "custom value" } ``` -------------------------------- ### Create Mock Sitecore Items with FakeItem Source: https://context7.com/smarchenko/sitecoredi.nsubstitute.helper/llms.txt Use FakeItem to create mock Sitecore Item objects with a fluent builder interface. It automatically configures common properties and the associated database. Supports implicit conversion to Sitecore Item and can be extended. ```csharp using NSubstitute; using Sitecore.Data; using Sitecore.Data.Items; using Sitecore.NSubstituteUtils; // Basic item creation with auto-generated ID and database var fakeItem = new FakeItem(); Item item = fakeItem; // Implicit conversion to Sitecore Item // Create item with specific ID and database var itemId = ID.NewID; var database = FakeUtil.FakeDatabase("master"); var customItem = new FakeItem(itemId, database); // Configure item properties using fluent API var productItem = new FakeItem() .WithName("Product-001") .WithDisplayName("Featured Product") .WithTemplate(ID.Parse("{76036F5E-CBCE-46D1-AF0A-4143F9B557AA}")) .WithPath("/sitecore/content/Products/Product-001") .WithField("Title", "Premium Widget") .WithField("Price", "99.99") .WithField(ID.Parse("{A4F985D9-98B3-4B52-AAAF-4344F6E747C6}"), "Description", "High-quality product"); // Access configured properties Item scItem = productItem; string title = scItem["Title"]; // Returns "Premium Widget" string price = scItem.Fields["Price"].Value; // Returns "99.99" string name = scItem.Name; // Returns "Product-001" ID templateId = scItem.TemplateID; // Returns the configured template ID // Create parent-child item hierarchies var parentItem = new FakeItem() .WithName("ParentFolder") .WithPath("/sitecore/content/ParentFolder"); var childItem1 = new FakeItem(database: parentItem.ToSitecoreItem().Database) .WithName("Child1"); var childItem2 = new FakeItem(database: parentItem.ToSitecoreItem().Database) .WithName("Child2"); parentItem .WithChild(childItem1) .WithChild(childItem2); Item parent = parentItem; int childCount = parent.Children.Count; // Returns 2 bool hasChildren = parent.HasChildren; // Returns true ID parentId = ((Item)childItem1).ParentID; // Returns parent's ID // Configure additional item properties var fullyConfiguredItem = new FakeItem() .WithName("ConfiguredItem") .WithLanguage("en-US") .WithVersion(1) .WithItemAccess() .WithItemEditing() .WithItemLinks() .WithItemLocking() .WithItemVersions() .WithStatistics() .WithAppearance() .WithPublishing() .WithUri(); // Retrieve item from database (automatically configured) Item retrievedItem = fullyConfiguredItem.ToSitecoreItem().Database.GetItem(fullyConfiguredItem.ID); ``` -------------------------------- ### Create Mock Sitecore Templates with FakeTemplate Source: https://context7.com/smarchenko/sitecoredi.nsubstitute.helper/llms.txt Use FakeTemplate to construct mock Sitecore Template definitions, including sections, fields, and base template inheritance. Templates are automatically registered with a TemplateEngine. ```csharp using Sitecore.Data; using Sitecore.Data.Templates; using Sitecore.NSubstituteUtils; // Create a basic template var templateId = ID.Parse("{AAA11111-1111-1111-1111-111111111111}"); var template = new FakeTemplate("ProductTemplate", templateId) .WithFullName("/sitecore/templates/Product") .WithIcon("Applications/32x32/document.png"); Template scTemplate = template; // Implicit conversion string name = scTemplate.Name; // Returns "ProductTemplate" // Create template with sections and fields var contentTemplateId = ID.Parse("{BBB22222-2222-2222-2222-222222222222}"); var contentTemplate = new FakeTemplate("ContentPage", contentTemplateId); // Add a section with fields var contentSection = contentTemplate.AddSection("Content", ID.NewID); contentSection .WithIcon("Apps/32x32/section.png") .WithSortorder(100); // Add fields to the section var titleField = contentSection.AddField("Title", ID.Parse("{CCC33333-3333-3333-3333-333333333333}")); titleField .WithType("Single-Line Text") .WithSortorder(10) .WithValidation(".+") .WithDefaultValue("Default Title"); var bodyField = contentSection.AddField("Body", ID.Parse("{DDD44444-4444-4444-4444-444444444444}")); bodyField .WithType("Rich Text") .WithSortorder(20) .WithSource("/sitecore/system/Settings/Html Editor Profiles/Rich Text Default"); // Add fields directly to template (creates section automatically) contentTemplate.AddField("MetaDescription", ID.Parse("{EEE55555-5555-5555-5555-555555555555}")); // Create template with base template inheritance var baseTemplateId = ID.Parse("{FFF66666-6666-6666-6666-666666666666}"); var derivedTemplate = new FakeTemplate("DerivedTemplate", ID.NewID) .WithBaseIDs(new[] { baseTemplateId }); // Configure standard values holder var standardValuesId = ID.Parse("{111AAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA}"); var templateWithStandardValues = new FakeTemplate("TemplateWithDefaults", ID.NewID) .WithStandardValues(standardValuesId); // Access template from engine Template retrievedTemplate = template.TemplateEngine.GetTemplate(templateId); ``` -------------------------------- ### Test code using static managers with FakeServiceProviderWrapper Source: https://context7.com/smarchenko/sitecoredi.nsubstitute.helper/llms.txt Use FakeServiceProviderWrapper to inject mocked Sitecore managers into static contexts. The wrapper automatically resets managers upon disposal. ```csharp using System; using NSubstitute; using Sitecore.Abstractions; using Sitecore.Data.Items; using Sitecore.Data.Managers; using Sitecore.NSubstituteUtils; // Testing code that uses static ItemManager [Test] public void TestCodeUsingStaticItemManager() { // Arrange: Create fake item and mock service var fakeItem = new FakeItem().WithName("TestItem"); Item item = fakeItem; var mockItemManager = Substitute.For(); mockItemManager.GetParent(item).Returns(item); mockItemManager.GetChildren(item).Returns(new ChildList(item, new ItemList())); var fakeServiceProvider = Substitute.For(); fakeServiceProvider.GetService(typeof(BaseItemManager)).Returns(mockItemManager); // Configure provider helper if needed fakeServiceProvider.GetService( typeof(ProviderHelper)) .Returns(Substitute.For>("/providers")); // Act: Use the wrapper to substitute static manager using (new FakeServiceProviderWrapper(fakeServiceProvider)) { // Code under test can now use ItemManager.GetParent(item) // and it will return our configured mock response var parent = ItemManager.GetParent(item); // Assert Assert.That(parent, Is.EqualTo(item)); } // Static managers are automatically reset when disposed } // Testing with multiple static managers [Test] public void TestCodeUsingMultipleStaticManagers() { var fakeItem = new FakeItem(); Item item = fakeItem; var mockItemManager = Substitute.For(); var mockTemplateManager = Substitute.For(); mockItemManager.GetItem(Arg.Any()).Returns(item); mockTemplateManager.GetTemplate(item).Returns(item.Template); var fakeServiceProvider = Substitute.For(); fakeServiceProvider.GetService(typeof(BaseItemManager)).Returns(mockItemManager); fakeServiceProvider.GetService(typeof(BaseTemplateManager)).Returns(mockTemplateManager); using (new FakeServiceProviderWrapper(fakeServiceProvider)) { // Both ItemManager and TemplateManager static calls // will use the mocked implementations // Your test code here } } ``` -------------------------------- ### Create Mock Template Sections with FakeTemplateSection Source: https://context7.com/smarchenko/sitecoredi.nsubstitute.helper/llms.txt Use FakeTemplateSection to create standalone or template-associated sections. Configure display properties like icon and sort order. Fields can be added to these sections. ```csharp using Sitecore.Data; using Sitecore.Data.Templates; using Sitecore.NSubstituteUtils; // Create a standalone section var sectionId = ID.Parse("{12345678-AAAA-BBBB-CCCC-DDDDDDDDDDDD}"); var section = new FakeTemplateSection(sectionName: "Data", sectionId: sectionId) .WithIcon("Applications/32x32/data.png") .WithSortorder(200); TemplateSection scSection = section; // Implicit conversion string sectionName = scSection.Name; // Returns "Data" // Add fields to the section var field1 = section.AddField("DataField1", ID.NewID); var field2 = section.AddField("DataField2", ID.NewID); // Create section associated with a template var template = new FakeTemplate("MyTemplate"); var templateSection = new FakeTemplateSection(template, "Content", ID.NewID) .WithSortorder(100); // Access section builder for advanced configuration TemplateSection.Builder builder = section.Builder; ``` -------------------------------- ### Extend FakeItem with Custom Methods Source: https://github.com/smarchenko/sitecoredi.nsubstitute.helper/blob/master/README.md Extend the functionality of FakeItem by creating static extension methods that interact with the underlying Sitecore item. ```C# public static class TestFakeItemExtensions { public static FakeItem WithItemHelp(this FakeItem item, ItemHelp itemHelp) { item.ToSitecoreItem().Help.Returns(itemHelp); return item; } } ``` -------------------------------- ### Create Mock Template Fields with FakeTemplateField Source: https://context7.com/smarchenko/sitecoredi.nsubstitute.helper/llms.txt FakeTemplateField allows creation of template fields with comprehensive configuration, including type, validation, source, and display properties. Localized properties and special field types can also be configured. ```csharp using Sitecore.Data; using Sitecore.Data.Templates; using Sitecore.Globalization; using Sitecore.NSubstituteUtils; // Create a standalone template field var fieldId = ID.Parse("{AAAABBBB-CCCC-DDDD-EEEE-FFFFFFFFFFFF}"); var templateField = new FakeTemplateField(fieldName: "ContentField", fieldId: fieldId) .WithType("Rich Text") .WithSource("/sitecore/system/Settings/Html Editor Profiles/Rich Text Full") .WithSortorder(100) .WithIsShared(false) .WithUnversioned(false) .WithDefaultValue("

Default content

"); TemplateField scTemplateField = templateField; // Implicit conversion string fieldType = scTemplateField.Type; // Returns "Rich Text" // Configure field with localized properties var localizedField = new FakeTemplateField(fieldName: "LocalizedField", fieldId: ID.NewID) .WithTitle("Display Title", Language.Parse("en")) .WithDescription("Field description text", Language.Parse("en")) .WithToolTip("Helpful tooltip text", Language.Parse("en")) .WithValidation("^[A-Za-z]+$") .WithValidationText("Only letters are allowed", Language.Parse("en")); // Configure field for special purposes var blobField = new FakeTemplateField(fieldName: "ImageField", fieldId: ID.NewID) .WithType("Image") .WithIsBlob(true) .WithSharedLanguageFallbackEnabled(true) .WithExcludeFromTextSearch(true) .WithResetBlank(false) .WithHelpLink("/docs/image-field-help"); // Access field builder for advanced configuration TemplateField.Builder builder = templateField.Builder; ``` -------------------------------- ### Create Mock Sitecore Fields with FakeField Source: https://context7.com/smarchenko/sitecoredi.nsubstitute.helper/llms.txt Use FakeField to build mock Sitecore Field objects with various properties. Fields can be standalone or associated with a FakeItem. Supports implicit conversion to Sitecore's Field type. ```csharp using Sitecore.Data; using Sitecore.Data.Fields; using Sitecore.NSubstituteUtils; // Create a standalone field with specific ID and value var fieldId = ID.Parse("{12345678-1234-1234-1234-123456789012}"); var fakeField = new FakeField(fieldId) .WithName("ProductDescription") .WithValue("This is a premium product with exceptional quality.") .WithType("Rich Text") .WithDisplayName("Product Description") .WithSection("Content") .WithToolTip("Enter the product description here") .WithValidation("[a-zA-Z0-9\\s]+") .WithValidationText("Only alphanumeric characters allowed"); Field field = fakeField; // Implicit conversion string value = field.Value; // Returns the configured value string type = field.Type; // Returns "Rich Text" bool hasValue = field.HasValue; // Returns true // Create field associated with an item var item = new FakeItem().WithName("TestItem"); var associatedField = new FakeField(fieldId, item) .WithValue("Field value on item") .WithName("CustomField") .WithCanRead(true) .WithCanWrite(true) .WithShared(false) .WithUnversioned(false) .WithTranslatable(true); // Configure field metadata var metadataField = new FakeField() .WithName("MetadataField") .WithValue("test value") .WithKey("metadatafield") .WithSortorder(100) .WithLanguage("en") .WithIsModified(false) .WithIsBlobField(false) .WithContainsStandardValue(false) .WithContainsFallbackValue(false) .WithInheritedValue("inherited default") .WithDefinition(); // Creates a fake TemplateField definition Field configuredField = metadataField; string key = configuredField.Key; // Returns "metadatafield" int sortOrder = configuredField.Sortorder; // Returns 100 ``` -------------------------------- ### Substitute BaseItemManager with FakeServiceProviderWrapper Source: https://github.com/smarchenko/sitecoredi.nsubstitute.helper/blob/master/README.md Replaces the default BaseItemManager implementation to allow testing of static ItemManager calls. This should be treated as a temporary solution while refactoring to dependency injection. ```C# [Test] public void SimleProviderWrapper_ShouldWork() { var item = FakeUtil.FakeItem(); var service1 = Substitute.For(); service1.GetParent(item).Returns(item); var fakeServiceProvider = Substitute.For(); fakeServiceProvider.GetService(typeof(BaseItemManager)).Returns(service1); fakeServiceProvider.GetService( typeof(ProviderHelper)) .Returns( Substitute.For>("/somepath")); using (new FakeServiceProviderWrapper(fakeServiceProvider)) { ItemManager.GetParent(item).Returns(item); } } ``` -------------------------------- ### Reset static Sitecore managers with StaticManagersUtils Source: https://context7.com/smarchenko/sitecoredi.nsubstitute.helper/llms.txt Manually reset Sitecore static managers to ensure test isolation. This is typically handled automatically by the wrapper. ```csharp using System; using Sitecore.Data.Managers; using Sitecore.NSubstituteUtils; // Reset all static managers (called automatically by FakeServiceProviderWrapper) StaticManagersUtils.ResetStaticManagers(); // Reset a specific static manager StaticManagersUtils.ResetStaticManager(typeof(ItemManager)); StaticManagersUtils.ResetStaticManager(typeof(TemplateManager)); StaticManagersUtils.ResetStaticManager(typeof(PublishManager)); StaticManagersUtils.ResetStaticManager(typeof(LanguageManager)); StaticManagersUtils.ResetStaticManager(typeof(LinkManager)); StaticManagersUtils.ResetStaticManager(typeof(MediaManager)); // Supported managers that can be reset include: // ItemManager, TemplateManager, PublishManager, HistoryManager, LanguageManager, // ThemeManager, CacheManager, FieldTypeManager, LanguageFallbackFieldValuesManager, // ValidatorManager, StandardValuesManager, JobManager, ControlManager, // PresentationManager, PreviewManager, MediaManager, MediaPathManager, // AccessRightManager, AuthorizationManager, RolesInRolesManager, UserManager, // DomainManager, FeedManager, LayoutManager, RuleManager, TicketManager, // DistributedPublishingManager, LanguageFallbackManager, EventManager, // LinkManager, SiteManager, AuthenticationManager, and more ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.