Sitecore developers often need to reference content items from their code. E.g.: a template or branch ID for an import function or reading a global setting that’s stored in the content tree. Using IDs is usually preferred over using paths, because paths may change. It’s considered good practice to keep those ID references in a class with constants, like this:
After recently contributing some serialization logic to Sitecore.FakeDb, I got the idea to write unit tests that validate if these constants have values that are actually in Sitecore. We can use TDS or Unicorn serialized data to validate this.
The following unit test does just that (uses NUnit, FluentAssertions, Sitecore.FakeDb and Sitecore.FakeDb.Serialization):
Just pass in the types (that have Sitecore IDs as static properties) using the “Values” attribute.
But I didn’t stop there. At my company, we’re currently working on a project that uses Glass Mapper. Glass Mapper can use attributes to link mapped classes to the correct Sitecore templates. And in a similar way, properties can be linked to field IDs.
I wanted to validate all those IDs as well, and also check if the field IDs are on the right templates.
That’s why I wrote the following unit test. It finds all the types that have attributes like this and deserializes the corresponding templates. It also checks if the fields are there.
To use it, you need to pass in one type from the assembly that you want to test (or multiple) using the “Values” attribute.
Since I’m quite new to using Glass Mapper, I’d be interested to get some feedback on this. I’m pretty sure there’s more that can be tested.