简体   繁体   English

单元测试实体框架

[英]Unit testing entity framework

When unit testing with NHibernate I will typically have tests that create and save an object, clear the session (session.Clear()) then retrieve the object from the database. 使用NHibernate进行单元测试时,我通常会创建和保存对象的测试,请清除会话(session.Clear()),然后从数据库中检索对象。

What's the equivalent of Session.Clear() with EF4? EF4相当于Session.Clear()?

Example test: 测试示例:

    [Test]
    public void Can_create_and_save_a_default_account()
    {
        var account = new Account();

        _db.Accounts.AddObject(account);
        _db.SaveChanges();

        int id = account.AccountId;

        // clear session

        var fromDb = _db.Accounts.SingleOrDefault(x => x.AccountId == id);
        Assert.IsNotNull(fromDb);
    }

那将重新创建您的DataContext派生的类(在您的情况下为_db )。

You could mock your remote database with in-memory database. 您可以使用内存数据库模拟远程数据库。 Here is example SO after each test you will start from scratch. 这是在每次测试之后的示例 SO,您将从头开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM