Karan
Karan

Reputation: 15104

How to unit test database migrations?

I am about to perform database migrations in MVC .NET. I was wondering how can I unit test this.

For example, I would like to apply the migration in this question: Rename a db column. How could I unit test this?


My thoughts:

  1. Migrate all existing migrations, except my latest one which I am going to test
  2. Add data to the context
  3. Apply new migration
  4. Test data still there

If my thoughts makes sense, any idea how to apply these to MVC .NET? Thanks!

Upvotes: 1

Views: 3301

Answers (1)

cincura.net
cincura.net

Reputation: 4150

For integration test. Just my rough idea. Probably depends on your environment - build server, DB server, deployment making, ...

You have to always have same (known) starting point with database. Either you'll create it manually and commit it into VCS and always manually update to M-1 (M=migration). Or just suppose all the migrations M-1 worked before (because it was tested) and create it automatically using i.e. migrate.exe. Then you try to do your steps and then test, preferably using different "channel" than EF, that the data is there, that the column is there etc. Just pure SQL through good old ADO.NET is enough here. Because it doesn't need to be versatile, you can create some simple helper(s) that will run the query using the well known Connection-Command-Reader path and return it as a raw data i.e. simple IEnumerable (I did that myself, through dynamic to make super simple.).

My advice is just to keep it simple, nothing fancy and clever. It's just to support testing.

Upvotes: 2

Related Questions