实体框架4.1-代码优先单元测试数据访问层 [英] Entitity Framework 4.1 - Code First- Unit testing data access layer

查看:70
本文介绍了实体框架4.1-代码优先单元测试数据访问层的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是.NET开发人员,正在为我的数据访问层编写测试.我有使用虚假存储库的测试-通过使用Moq和Ninject已经实现了这一目标.

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.

我开始了解EntityFramework 4.1 Code First模型,我想为CRUD例程创建一个原型.这是一个MVC应用程序,因此上下文不会跟踪我的实体.

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.

对我来说,编写正在对数据库进行更改的测试感到不对.然后,每次我要运行这些测试时,我都必须清除数据库.这是测试CRUD例程的唯一方法吗?

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?

谢谢

推荐答案

如果不访问数据,如何期望测试数据访问?是的,应该对真实数据库进行数据访问测试.有一个非常简单的解决方法来解决您的问题.在测试结束时进行测试事务和回滚更改.您可以使用这样的基类(NUnit):

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;
        }
    }
}

这篇关于实体框架4.1-代码优先单元测试数据访问层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆