我正在尝试为使用实体框架的域编写一套数据库集成测试。我更喜欢在某些情况下自动固定对象。我理想的语法是这样的
[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 博客之后,我对这些作品如何相互作用感到有些困惑。
工厂调用期间的实例MyDbContext
不是我传递给的实例Inject()