【问题标题】:Using autofixture in my data integration tests to create proxies在我的数据集成测试中使用 autofixture 创建代理
【发布时间】:2013-01-18 01:32:09
【问题描述】:

我正在尝试为我的域编写一套使用实体框架的数据库集成测试。我更喜欢在某些情况下自动固定对象。我理想的语法是这样的

[TestMethod]
public void AutofixtureMyEntityEntity()
{
    var fixture = new Fixture();

    fixture.Customize<MyEntity>(
      c => c.FromFactory<MyDbContext>(ctx => ctx.Set<MyEntity>().Create()));

    using (var context = new MyDbContext())
    {
        fixture.Inject(context);
        var entity = fixture.CreateAnonymous<MyEntity>();
        context.Set<MyEntity>().Add(entity);
        context.SaveChanges();
    }
}

[TestMethod]    
[ExpectedException(typeof(InvalidOperationException))]
public void AutoFixtureMyEntityEntityWithoutInjection()
{
    var fixture = new Fixture();

    fixture.Customize<MyEntity>(
       c => c.FromFactory<MyDbContext>(ctx => ctx.Set<MyEntity>().Create()));

    using (var context = new MyDbContext())
    {
        var entity = fixture.CreateAnonymous<MyEntity>();
        context.Set<MyEntity>().Add(entity);
        context.SaveChanges();
    }
}

显然,这是行不通的,因为CreateAnonymous() 不期望工厂的输入参数。我只能假设我对FromFactory() 提供的内容有错误的理解。虽然评论说,

/// Specifies that a specimen should be created in a particular way, using a single input
/// parameter for the factory.

在阅读了ploehs blog 之后,我对这些部分如何相互作用感到有些困惑。

工厂调用时MyDbContext的实例不是我传递给Inject()的实例

【问题讨论】:

  • 您可以使用fixture.Inject( context),这意味着对上下文的任何要求都将使用该实例。那行得通吗? (老实说,你的问题很混乱——你有很多建议的方法,很高兴知道你已经尝试过了,但你遇到的单个问题对我来说并不是 100% 清楚)
  • 鲁本,我试图收紧这个例子。在没有任何运气的情况下,我在 Inject 上搞砸了,我试图在每次调用创建匿名之前向工厂提供一个实例。

标签: integration-testing autofixture


【解决方案1】:

这样的东西有用吗?

var fixture = new Fixture();
fixture.Customize<MyEntity>(c => c
    .FromFactory<MyDbContext, MyEntity>(ctx => ctx.Set<MyEntity>.Create()));

using (var context = new MyDbContext())
{
    fixture.Inject(context);
    var item = fixture.CreateAnonymous<MyEntity>();
    context.Set<MyEntity>().Add(item);
    context.SaveChanges();
}

免责声明:我没有尝试编译这个...


FWIW,如果您使用带有 AutoFixture 的 xUnit.net,您可以将测试简化为:

[Theory, MyAutoData]
public void TheTest([Frozen]MyDbContext context, MyEntity item)
{
    context.Set<MyEntity>().Add(item);
    context.SaveChanges();
}

【讨论】:

  • 谢谢,看来我需要自定义然后提供注入,几个扩展方法将提供一个非常灵活的工具来编写针对我的域的集成测试。将来可能会针对任何DataAnnotations 为夹具添加一些逻辑。
  • 我添加了一个关于让它变得更简单的预告片。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-26
  • 1970-01-01
  • 1970-01-01
  • 2017-09-13
相关资源
最近更新 更多