Entity Framework primary modular codes that require an empty database

I have a code that first uses the EF code that I want to test Unit in my unit test, I want an empty real base to be created at the beginning of the test , so I did:

    [TestInitialize]
    public void Initialize()
    {
        Database.SetInitializer(new DropCreateDatabaseAlways<MyContext>());

    }

    [TestCleanup]
    public void CleanUp()
    {

        MyContext db = new MyContext();
        db.Database.Delete();
    }

but due to the fact that the tests are executed in parallel, this does not work, so I conducted an order test with my tests, and also has problems, because the database is sometimes not discarded, because it is used ... Someone has a better strategy ? I thought maybe each test will create its own database? if it is a good idea, how can I achieve this?

+4
source share
2

,

[TestClass]
public class UnitTestClass
{
    private static string testConnString;


    [TestInitialize]
    public void Initialize()
    {
        testConnString = GetTestConnString();
        using (MyContext db = new MyContext(testConnString, new DropCreateDatabaseAlways<MyContext>()))
        {
            db.UnderlyingContext.Connection.Open();
        }

    }


    [TestMethod]
    public void TestMethod1()
    {
    }

    [TestCleanup]
    public void CleanUp()
    {

        using (MyContext db = new MyContext(testConnString))
        {
            db.Database.Delete();
        }
    }

    private static string GetTestConnString()
    {
        SqlConnectionStringBuilder csb = new SqlConnectionStringBuilder();
        csb.DataSource = @"MYPC\SQLEXPRESS"; // Replace it with your SQL-server name
        csb.InitialCatalog = "DB"+Guid.NewGuid().ToString().Replace("-","");
        csb.IntegratedSecurity = true;
       return csb.ToString();
    }
}


public class MyContext : DbContext
{

    private static IDatabaseInitializer<MyContext> _Initializer;
    public MyContext(string connString, IDatabaseInitializer<MyContext> initializer = null)
        : base(connString)
    {
        _Initializer = initializer;
    }

    public ObjectContext UnderlyingContext
    {
        get { return (this as IObjectContextAdapter).ObjectContext; }
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        if (_Initializer != null)
        {
            Database.SetInitializer(_Initializer);
        }
        base.OnModelCreating(modelBuilder);
    }

}
+1

""? ? DB, SQLite, . , . . . , Google .

. , . , .

- . . , , .

+1

Source: https://habr.com/ru/post/1541222/


All Articles