Created
September 5, 2012 11:39
-
-
Save WizzApp/3635399 to your computer and use it in GitHub Desktop.
Base class for db integration tests with EF and xUnit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="utf-8" ?> | |
<configuration> | |
<appSettings> | |
<!-- This parameter must match with the parameter in the entity connection string below --> | |
<add key="Database" value="TestDB" /> | |
</appSettings> | |
<connectionStrings> | |
<add name="ObjectContext" connectionString="metadata=res://*/Entities.csdl|res://*/Entities.ssdl|res://*/Entities.msl;provider=System.Data.SqlClient;provider connection string="Data Source=(local);Database=TestDB;Integrated Security=True;MultipleActiveResultSets=True;Application Name=EntityFramework"" providerName="System.Data.EntityClient" /> | |
</connectionStrings> | |
</configuration> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Configuration; | |
using System.Data.Objects; | |
using System.Data.SqlClient; | |
namespace Varta.VartaGuide.Tests.Integration | |
{ | |
public class EFDatabaseTest<CONTEXTTYPE> where CONTEXTTYPE:ObjectContext, new() | |
{ | |
public DbContext DbContext { private set; get; } | |
public EFDatabaseTest() | |
{ | |
DbContext = new DbContext(); | |
string database = ConfigurationManager.AppSettings.Get("Database"); | |
// Create db if necessary | |
var con = new System.Data.SqlClient.SqlConnection( | |
String.Format("Data Source={0};Integrated Security=SSPI;", | |
DbContext.Connection.DataSource)); | |
con.Open(); | |
System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand("SELECT name FROM sys.databases WHERE name = @dbName"); | |
command.Connection = con; | |
var param = command.CreateParameter(); | |
param.ParameterName = "@dbName"; | |
param.Value = database; | |
command.Parameters.Add(param); | |
var reader = command.ExecuteReader(); | |
bool databaseExists = reader.HasRows; | |
reader.Close(); | |
if (databaseExists) | |
{ | |
var commandCreateDb = new SqlCommand(String.Format("DROP DATABASE {0}", database)); | |
commandCreateDb.Connection = con; | |
commandCreateDb.ExecuteNonQuery(); | |
} | |
con.Close(); | |
DbContext.CreateDatabase(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment