Entitity Framework 4.1 - Code First- Unit testing data access layer

回眸只為那壹抹淺笑 提交于 2019-12-20 06:37:38

问题


I'm a .NET developer and I'm writing tests for my data access layer. I have tests that use fake repository - I have achieved that by using Moq and Ninject.

I'm getting my head around EntityFramework 4.1 Code First model and I'd like to create a prototype for CRUD routines. It's an MVC app, so my entities won't be tracked by a context.

To me it feels wrong that I'm writing tests that will make changes to the database. I will then have to clear the database each time I want to run these tests. Is this the only way to test CRUD routines?

Thank you


回答1:


How do you expect to test data access if you don't access the data? Yes data access should be tested against real database. There is very simple workaround for your problem. Make your test transactional and rollback changes at the end of the test. You can use base class like this (NUnit):

[TestFixture]
public abstract class BaseTransactionalTest
{
    private TransactionalScope _scope = null;

    [SetUp]
    public void Initialize()
    {
        _scope = new TransactionalScope(...);        
    }

    [TearDown]
    public void CleanUp()
    {
        if (_scope != null)
        {
            _scope.Dispose();
            _scope = null;
        }
    }
}


来源:https://stackoverflow.com/questions/7023200/entitity-framework-4-1-code-first-unit-testing-data-access-layer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!