Home > Computers and Internet > Unit testing with SqlServerMigrationGenerator

Unit testing with SqlServerMigrationGenerator

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.

public void GetAddColumnSql_DateCreated_ReturnsCorrectScript() {
    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);

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

    Assert.AreEqual("ALTER TABLE [Dbo].[Test] ADD [DateCreated] [datetime2](7) CONSTRAINT DF_Dbo_Test_DateCreated DEFAULT GETDATE()", result);
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: