I am writing integration tests to verify the behaviour in my repositories. The problem I run into is that I want to start with a clean database for every test. I managed to do so by writing the SetUp as follows:
[SetUp]
public void SetUp()
{
_applicationContext = new TestApplicationContext();
_applicationContext.Database.Connection.Close();
_applicationContext.Database.Delete();
_applicationContext.Database.Create();
_tenantRepository = new TenantRepository(_applicationContext);
_userRepository = new UserRepository(_applicationContext);
}
The TestApplicationContext sets the database name to TestDatabase.
This works fine until I want to check the actual database for the result of my test. Then I make a connection from MSSQL server to the same database, which won’t close until I either:
- shut down MSSQL server
- delete the database with the option “close all connections”
The only way I found is via SQL commands. Maybe it’s because of my n00b knowledge regarding MSSQL, but I was kinda hoping for a “close connection” button / option.
How can I close the connection to the database from MSSQL server?
Or, is there a way I can do this programmatically from C#?
UPDATE:
Maybe I wasn’t very clear. But the test SetUp fails after I opened MSSQL and viewed the contents of a table. This is because MSSQL also creates a connection to the TestDatabase, and my integration test is not able to close that connection. So I am looking for a solution that allows me to close the connection I created from MSSQL server.
You can work around the connection problem if instead of dropping and re-creating whole database you just drop and re-create selected (or all tables).
You could create little script that will do it for you in a way that you do not need to hard-code table names:
http://www.apexure.com/blog/2010/07/29/delete-all-tables-in-sql-server-database/
Alternatively, Julia Lerman in her book “Programming Entity Framework: Code First” mentiones this approach in more mature form, as incorporated as a custom database initializer: