Unit tests with input data as assembly resources

By Markus Johansson

When running unit tests over "complex" data ie. an html, XML, or json-file it's sometimes good to keep this data in its own file and not in the C# code like this:

The example above is from one of our utility projects for Umbraco where we're parsing the grid to remove any empty p-tags from the end of a Rich Text Editor. To really know that this works and also keeps working we've created unit tests for different kinds of grid input.


First off, we need to include the files in the project and then set there "Build Action" to "Embedded Resource", right-click on the file, and choose "Properties" to see this options pane:


After this we can read the content of the files like this:

var content = new AssemblyTestData<MyUnitTestClass>(".Files.").ReadString("test-data.json");

Here's the code for the AssemblyTestData-class:

// <summary>
/// Utility to read content of embedded assembly resources
/// </summary>
/// <typeparam name="T">The calling type, used to get the resource namespace</typeparam>
public class AssemblyTestData<T>
    private readonly string _additionalNameSpace;

    /// <summary>
    /// </summary>
    /// <param name="additionalNameSpace">If the files to read is in another namespace than the calling class, add this here ie ".Files</param>
    public AssemblyTestData(string additionalNameSpace = "")
        _additionalNameSpace = additionalNameSpace;

    public string ReadString(string filename)
        var bytes = ReadBytes(filename);
        return Encoding.UTF8.GetString(bytes)
            .Trim(new char[]{'\uFEFF','\u200B'}); // Removes boom-chars


    public byte[] ReadBytes(string filename)
        var type = typeof(T);
        var assembly = type.Assembly;
        var stream = assembly.GetManifestResourceStream(type.Namespace + _additionalNameSpace + filename);

        using (var memoryStream = new MemoryStream())
            return memoryStream.ToArray();

Happy testing!


More blog posts

15 januari 2021

Umbraco and MiniProfiler