This is a small library of static methods to help you write integration tests for SQL Server. It creates databases dynamically on your localdb instance, and frees you from maintaining a connection string and related config overhead. You can also initialize databases with seed objects and data via SQL statements or any arbitrary initialization.
To use, install nuget package SqlServer.LocalDb.Testing
Then, in your integration tests that require a LocalDb connection, you can write code like this:
using (var cn = LocalDb.GetConnection("sample"))
{
// whatever testing you need to do
}
This will open or create a database named sample
at (localdb)\mssqllocaldb
I didn't try too hard to implement deletion of sample databases because I have found deleting databases at runtime to be pretty fussy. I figure if you are running tests in an environment like AppVeyor, then you get a clean environment with every build. So, I felt that deleting databases as a cleanup activity was just not necessary.
I looked around and saw a couple other libraries doing exactly what I set out to do here, which was interesting to see. Maybe I should've looked around before writing mine, but I enjoy stuff like this -- so here we are!
- Create database with sample model, sample model is here, and random data creation is here
- Drop sample db on test class startup
- Another test class initialize example
- Yet another test class initialize, with random data, using my Test Data Generation library.
- Side note: Random data persistence is handled by my BulkInsert helper from my SqlIntegration project.
Reference LocalDb.cs
- string GetConnectionString (string databaseName)
- SqlConnection GetConnection (string databaseName, IEnumerable initializeStatements)
- void ExecuteInitializeStatements (SqlConnection cn, IEnumerable statements)
- SqlConnection GetConnection (string databaseName, [ Action initialize ])
- bool TryDropDatabase (string databaseName, string message)
- bool TryDropDatabaseIfExists (string databaseName, string message)
- bool ObjectExists (SqlConnection connection, string objectName)
- void ExecuteIfExists (SqlConnection connection, string objectName, string execute)
If by a crazy turn of events, you find this useful, please consider buying me a coffee.