How to Test with Rainbow Deserializer to Sitecore FakeDb

April 23, 2019

My test utility, Rainbow Deserializer to Sitecore FakeDb, can be added to a test project through NuGet or you can build it from the source at Github. Nuget has the advantage of including all dependencies so you can get FakeDb and Rainbow all at once. If you Manage NuGet Packages from Visual Studio, you can find the project by searching for RainbowDeserializerToFakeDb.

Once you have referenced the project, you can create a shared method for your tests that will return a FakeDb with your desired data. The example creates a FakeDb and hydrates it with the Rainbow serialized files in the referenced templates and content folders.

    public Sitecore.FakeDb.Db WithSerializedFiles()
    {
        var db = new Sitecore.FakeDb.Db();
        db.AddYml(true,
            @"c:\project\src\serialization\templates",
            @"c:\project\src\serialization\content"
            );
        return db;
    }
        

Now in your test method, you can call this in a using statement like you would normally use FakeDb. In the example below, we call our new method and use the returned FakeDb to grab a predetermined item.

    [TestMethod]
    public void Hero_HasImage()
    {
        // Arrange
        using (Db db = WithSerializedFiles())
        {
            HeroRepository repo = new HeroRepository();

            // Act
            Hero model = repo.Get(db.GetItem(Ids.Content.DefaultHero));

            // Assert
            Assert.IsNotNull(model.Image);
        }
    }
        

FakeDb also sets Sitecore's context database so code that makes calls to it will continue to function. With some additional setup you can get this to work with dependency injection and Glass Mapper. I'll write a followup post on how I got repositories to work that use GlassMapper's SitecoreContext.