I'm struggling with faking my DbContext classes. Let's say I have my DbContext with entity Cars. I did manage to fake a list of Cars, but now I don't know how to fake adding (so adding would add a new Car to my fake list).
I have my list of Cars (this class is generic, but to give an easy example I've changed it to Cars):
private List<Cars> Data;
And property which returns Moq object:
public Mock<DbSet<Cars>> MockSet
{
get
{
var mock = new Mock<DbSet<Cars>>();
mock.As<IQueryable<Cars>>().Setup(m => m.Provider).Returns(Data.Provider);
mock.As<IQueryable<Cars>>().Setup(m => m.Expression).Returns(Data.Expression);
mock.As<IQueryable<Cars>>().Setup(m => m.ElementType).Returns(Data.ElementType);
mock.As<IQueryable<Cars>>().Setup(m => m.GetEnumerator()).Returns(Data.GetEnumerator());
//To fake Include:
mock.Setup(m => m.Include(It.IsAny<String>())).Returns(mock.Object);
return mock;
}
}
If I have this object, I can fake my entity:
Mock<DBContext> dbMoq = new Mock<DbContext>();
dbMoq.Setup(x => x.Cars).Returns(carsMoq.MockSet.Object);
Now I'm able to run my test without any problem, but if within my test method someone will add a new Car, I won't be able to check it:
this.dbContext.Cars.Add(car);
I did try to mock Add method and add new entity to my fake list:
dbMoq.Setup(x => x.Cars.Add(It.IsAny<Cars>())).Callback<Cars>((c) => this.CarsList.Add(c));
But it seems to do nothing. Any clue for that ? Is this approach a good one ?
Aucun commentaire:
Enregistrer un commentaire