c# - 如何使用 Autofixture 创建和填充模拟类?

标签 c# autofixture nsubstitute

目前我正在使用 EF6 在 UnitOfWork 中实现我的存储库。我还创建了一个内存中模拟实现 (MockUnitOfWork & MockRepository),以便我可以在单元测试中使用它们,但是我现在必须处理对象的繁琐设置。

这不是 Autofixture 的设计目的吗?我将如何获得可以在我的测试中使用的 MockUnitOfWork,其中包含已填充的 FooBarr 存储库?我正在使用 NSubstitute 作为我的模拟框架。

工作单元

public interface IUnitOfWork
{
    void Save();
    void Commit();
    void Rollback();

    IRepository<Foo> FooRepository { get; }
    IRepository<Bar> BarRepository { get; }
}

IRepository

public interface IRepository<TEntity> where TEntity : class
{
    Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null, string         includeProperties = "");

    IEnumerable<TEntity> Get(Expression<Func<TEntity, bool>> filter = null, Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null);
    TEntity GetByID(object id);

    void Insert(TEntity entity);
    void Delete(object id);
    void Delete(TEntity entityToDelete);
    void Update(TEntity entityToUpdate);
}

最佳答案

您正试图在这里进行功能测试,因此拥有一个功能数据库是明智的。

EF 可以使用测试连接字符串在设置和拆卸方法中重新创建和销毁数据库。这将为您的测试提供真实的功能测试环境,以模拟真实环境。

例如:

        [TestFixtureSetUp]
        public static void SetupFixture() //create database
        {
            using (var context = new XEntities())
            {
                context.Setup();
            }
        }

        [TestFixtureTearDown]
        public void TearDown() //drop database
        {
            using (var context = new XEntities())
            {
                context.Database.Delete();
            }
        }

        [SetUp]
        public void Setup() //Clear entities before each test so they are independent
        {
            using (var context = new XEntities())
            {
                foreach (var tableRow in context.Table)
                {
                    context.Table.Remove(tableRow);
                }
                context.SaveChanges();
            }
        }

关于c# - 如何使用 Autofixture 创建和填充模拟类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22342305/

相关文章:

c# - Environment.CurrentDirectory 和 Directory.GetCurrentDirectory 有什么区别?

c# - C# 中的作用域变量?

c# - 获取BuiltInParameterGroup枚举值的人类可读名称

testing - NSubstitute 模拟 NLog 记录器失败

c# - NSubstitute - 使成员返回 lambda 调用的结果

c# - ASP.Net MVC : How to display a byte array image from model

c# - 随机枚举生成

dependency-injection - 为什么带有 AutoMoqCustomization 的 Autofixture 在类被密封时不再提示缺少无参数构造函数?

c# - AutoFixture:如何从 System.Type 创建匿名

c# - 模拟 Excel.worksheet 时如何避免使用动态?