Created
March 3, 2023 13:35
-
-
Save sshushliapin/41f6e2f07048a5a95cb3018f9c318c57 to your computer and use it in GitHub Desktop.
The list of AutoFixture customizations intended to simplify unit testing in Sitecore projects
This file contains 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
namespace AutoSitecoreCustomizations | |
{ | |
public class AutoNSubstituteDataAttribute : AutoDataAttribute | |
{ | |
public AutoNSubstituteDataAttribute() | |
: base(() => new Fixture() | |
.Customize(new AutoNSubstituteCustomization()) | |
.Customize(new DatabaseCustomization()) | |
.Customize(new ItemCustomization()) | |
.Customize(new FieldCustomization())) | |
{ | |
} | |
} | |
internal class DatabaseCustomization : ICustomization | |
{ | |
public void Customize(IFixture fixture) | |
{ | |
fixture.Inject(Substitute.For<Database>()); | |
} | |
} | |
internal class ItemCustomization : ICustomization | |
{ | |
public void Customize(IFixture fixture) | |
{ | |
fixture.Customize<Item>(x => | |
x.FromFactory(() => CreateItem(fixture)) | |
.OmitAutoProperties() | |
); | |
} | |
private static Item CreateItem(ISpecimenBuilder fixture) | |
{ | |
var item = Substitute.For<Item>( | |
fixture.Create<ID>(), | |
ItemData.Empty, | |
fixture.Create<Database>()); | |
item.Name.Returns("item_" + fixture.Create<string>()); | |
item.Children.Returns(Substitute.For<ChildList>(item, new List<Item>())); | |
item.Fields.Returns(Substitute.For<FieldCollection>(item)); | |
item.Axes.Returns(Substitute.For<ItemAxes>(item)); | |
var language = Language.Parse("en"); | |
item.Language.Returns(language); | |
item.Languages.Returns(new[] { language }); | |
item.OriginalLanguage.Returns(language); | |
var templateId = fixture.Create<ID>(); | |
var template = Substitute.For<TemplateItem>(Substitute.For<Item>( | |
templateId, | |
ItemData.Empty, | |
fixture.Create<Database>())); | |
template.ID.Returns(templateId); | |
item.Template.Returns(template); | |
item.TemplateID.Returns(templateId); | |
item.Version.Returns(Version.First); | |
item.Versions.Returns(Substitute.For<ItemVersions>(item)); | |
item.Versions.Count.Returns(1); | |
return item; | |
} | |
} | |
internal class FieldCustomization : ICustomization | |
{ | |
public void Customize(IFixture fixture) | |
{ | |
fixture.Customize<Field>(x => | |
x.FromFactory(() => CreateField(fixture)) | |
.OmitAutoProperties() | |
); | |
} | |
private static Field CreateField(ISpecimenBuilder fixture) | |
{ | |
var item = fixture.Create<Item>(); | |
var fieldId = fixture.Create<ID>(); | |
var field = Substitute.For<Field>( | |
fieldId, | |
item); | |
field.Database.Returns(item.Database); | |
field.Name.Returns($"field_{fieldId}"); | |
return field; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment