如何使用 Autofixture 创建和填充我的模拟类?

2024-02-28

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

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

工作单元

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

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

信息库

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 可以使用测试连接字符串在设置和拆卸方法中重新创建和销毁数据库。这将为您的测试提供一个真实的功能测试环境,以模仿真实环境进行操作。

Ex:

        [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();
            }
        }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 Autofixture 创建和填充我的模拟类? 的相关文章

随机推荐