So i'm working on a code generator at work, and obviously i want to do it the TDD way. I wasn't quite sure how i could make sure that it would be easy to test.
This is what i came up with:
[TestClass]public abstract class GeneratorTests<T> where T : new()
{private SourceStringBuilder _expectedSourceStringBuilder;
private SourceStringBuilder _generationSourceStringBuilder;
private T _generator;protected SourceStringBuilder GenerationSourceStringBuilder
{get { return _generationSourceStringBuilder; }
}
protected SourceStringBuilder ExpectedSourceStringBuilder
{get { return _expectedSourceStringBuilder; }
}
protected T Generator {get { return _generator; }
}
[TestInitialize]public void SetUp()
{_generationSourceStringBuilder = new SourceStringBuilder(0);
_expectedSourceStringBuilder = new SourceStringBuilder(0);
_generator = new T();}
protected void AssertThatGeneratedCodeContainsExpectedCode()
{ Assert.IsTrue(GenerationSourceStringBuilder.ToString().Contains(ExpectedSourceStringBuilder.ToString()));
}
}
This base class can be reused for each test class that tests a specific generator:
[TestClass]public class StandardPropertyGeneratorTests : GeneratorTests<StandardPropertyGenerator>
{ [TestMethod]public void GenerateCodeFor_SimpleColumn_GeneratedCodeContainsCamelCasedPrivateFieldDeclaration()
{ColumnInfo column = CreateColumn("Test", DataType.Int32);
Generator.GenerateCodeFor(column, GenerationSourceStringBuilder);
ExpectedSourceStringBuilder.AppendLine("private Int32 _test;");AssertThatGeneratedCodeContainsExpectedCode();
}
private ColumnInfo CreateColumn(string name, DataType dataType)
{return CreateColumn(name, dataType, false);
}
private ColumnInfo CreateColumn(string name, DataType dataType, bool nullable)
{ColumnInfo column = new ColumnInfo();
column.LogicalName = name;
column.DataType = dataType;
column.Nullable = nullable;
return column;}
}
How clear is this to someone who has no or hardly no knowledge of what these generators and SourceStringBuilders do? I'd like to know so if you have an opinion, please comment below ![]()