Sto provando a configurare un DbSet fittizio a scopo di test. Ho usato il tutorial qui, http://www.loganfranken.com/blog/517/mocking-dbset-queries-in-ef6/ e leggermente modificato, quindi chiamare GetEnumerator restituisce un nuovo enumeratore ogni volta (un altro problema che stavo avendo). Tuttavia, ho difficoltà ad aggiungere elementi a DbSet.Come aggiungere un elemento a un DbSet fittizio (usando Moq)
L'output è preCount = 3 postCount = 3. Tuttavia, mi aspetto che sia precount = 3 postCount = 4. Qualsiasi aiuto è molto apprezzato.
static void Main(string[] args)
{
Debug.WriteLine("hello debug");
List<string> stringList = new List<string>
{
"a", "b", "c"
};
DbSet<string> myDbSet = GetQueryableMockDbSet(stringList);
int preCount = myDbSet.Count();
myDbSet.Add("d");
int postCount = myDbSet.Count();
Debug.WriteLine("preCount = " + preCount + " postCount = " + postCount);
}
private static DbSet<T> GetQueryableMockDbSet<T>(List<T> sourceList) where T : class
{
var queryable = sourceList.AsQueryable();
var dbSet = new Mock<DbSet<T>>();
dbSet.As<IQueryable<T>>().Setup(m => m.Provider).Returns(queryable.Provider);
dbSet.As<IQueryable<T>>().Setup(m => m.Expression).Returns(queryable.Expression);
dbSet.As<IQueryable<T>>().Setup(m => m.ElementType).Returns(queryable.ElementType);
dbSet.As<IQueryable<T>>().Setup(m => m.GetEnumerator()).Returns(() => queryable.GetEnumerator());
return dbSet.Object;
}
metodo molto bello per incapsulare la creazione del dbSet. Qualche possibilità che hai aggiornato per supportare query asincrone? –
Questo, almeno per il momento con .net core 1.0, risponderà al problema asincrono: [Come prendere in giro un repository asincrono con Entity Framework Core] (https://stackoverflow.com/questions/40476233/how-to-mock -an-async-repository-with-entity-framework-core) –