Testing With A Fake DbContext and Autofixture and Moq

自古美人都是妖i 提交于 2019-12-05 17:42:29

A minor point... In stuff like:

var ciudades_fixture = fixture.Build<Ciudad>().CreateMany<Ciudad>();

The second type arg is unnecessary and should be:

var ciudades_fixture = fixture.Build<Ciudad>().CreateMany();

I really understand why you need a FakeDbSet and the article is a bit TL;DR... In general, I try to avoid faking and mucking with ORM bits and instead dealing with interfaces returning POCOs to the max degree possible.

That aside... The reason the normal syntax for initialising the list works is that there is an Add (and IEnumerable) in DBFixture. AutoFixture doesn't have a story for that pattern directly (after all it is compiler syntactic sugar and not particularly amenable to reflection or in line with any other conventions) but you can use AddManyTo as long as there is an ICollection in play. Luckily, within the impl of FakeDbSet as in the article, the following gives us an in:-

public ObservableCollection<T> Local
{
    get { return _data; }
}

As ObservableCollection<T> derives from ICollection<T>, you should be able to:

var ciudades = new FakeDbSet<Cuidad>();
fixture.AddManyTo(ciudades.Local);

var mockData = new Mock<IContext>();
mockData.Setup(m => m.Ciudades).Returns(ciudades);

It's possible to wire up a customization to make this prettier, but at least you have a way to manage it. The other option is to have something implement ICollection (or add a prop with a setter taking IEnumerable<T> and have AF generate the parent object, causing said collection to be filled in.


Long superseded side note: In your initial question, you effectively have:

fixture.Build<FakeDbSet<Ciudad>>().CreateMany()

The problem becomes clearer then - you are asking AF to generate Many FakeDbSet<Ciudad>s, which is not what you want.

I haven't used AutoFixture in a while, but shouldn't it be:

var ciudades = new FakeDbSet<Ciudad>();
fixture.AddManyTo(ciudades);

for the moment I end doing this, I will keep reading about how use automoq, cause I'm new in this

var fixture = new Fixture();
var ciudades_fixture = fixture.Build<Ciudad>().CreateMany<Ciudad>();
var ciudades = new FakeDbSet<Ciudad>();
foreach (var item in ciudades_fixture)
{
    ciudades.Add(item);
}
var mockData = new Mock<IContext>(); 
fixture.Create<Mock<IContext>>();
mockData.Setup(r => r.Ciudades).Returns(ciudades);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!