Archive

Archive for October, 2015

Unit testing with SqlServerMigrationGenerator

October 27, 2015 Leave a comment

You may have noticed that all of the Generate(…) methods that you would be overriding in a custom Migration class are marked as protected, not public. This means you can’t directly test them in your unit tests.

Luckily we can take advantage of the way the Migration class is built and use the Generate(IEnumerable, string) method for our testing. IT does result in the creation of some extra objects, like a DbConnection (although it is never actually connected to a database). The second parameter takes a SQL version number.

Inside of this method, Microsoft initializes DbProvider things, and then runs through the collection of MigrationOperation and returns a collection of IEnumerable. So your unit test can simply check the first result the return value and pull the SQL from there. While this does make your test a little brittle (since you’re comparing strings that can be somewhat long), a little extra care and some code to clean up extra whitespace goes a long way.

[TestMethod]
public void GetAddColumnSql_DateCreated_ReturnsCorrectScript() {
    //arrange
    var columnName = "DateCreated";
    var columnType = "datetime2";
    var tableInfo = new DatabaseTable("Dbo.Test");
    var columnInfo = new ColumnModel(PrimitiveTypeKind.DateTime) {
        Name = columnName,
        StoreType = columnType
    };

    var addOperation = new AddColumnOperation("Dbo.Test", columnInfo);

    //act
    var result = (new StandardSqlServerSqlGenerator().Generate(new List {addOperation }, "2008")).First().Sql;

    //assert
    Assert.AreEqual("ALTER TABLE [Dbo].[Test] ADD [DateCreated] [datetime2](7) CONSTRAINT DF_Dbo_Test_DateCreated DEFAULT GETDATE()", result);
}