Last active
December 15, 2015 14:58
-
-
Save GuyHarwood/5278259 to your computer and use it in GitHub Desktop.
Base Test class with Lazy Entity Framework Context and database Initialisation.
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.Data.Entity; | |
using System.Diagnostics; | |
using NUnit.Framework; | |
namespace EntityFrameworkTests | |
{ | |
//TODO replace this stub with your own | |
public class MyDataContext : DbContext | |
{} | |
[TestFixture] | |
public abstract class DataTest | |
{ | |
private readonly Lazy<MyDataContext> _dbContext = new Lazy<MyDataContext>(CreateContext, false); | |
private static MyDataContext CreateContext() | |
{ | |
var context = new MyDataContext(); | |
if (context.Database.Exists()) | |
context.Database.Delete(); | |
context.Database.Create(); | |
return context; | |
} | |
protected MyDataContext DataContext | |
{ | |
get { return _dbContext.Value; } | |
} | |
/// <summary> | |
/// Inheritors should implement this to include their own test teardown code | |
/// </summary> | |
protected abstract void OnTearDown(); | |
[TearDown] | |
public void Destroy() | |
{ | |
if (!_dbContext.IsValueCreated) | |
return; | |
try | |
{ | |
_dbContext.Value.Database.Delete(); | |
} | |
catch (Exception ex) | |
{ | |
Assert.Inconclusive("Could not delete database, it may need to be removed manually.\n Check connection string for database location detail.\n Error Message:{0}", ex.Message); | |
} | |
finally | |
{ | |
if (_dbContext != null) | |
_dbContext.Value.Dispose(); | |
} | |
this.OnTearDown(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment