I am trying to mock a DbSet<> in Moq where I can add to the list of entities in the DbSet<>. In other words, a mutable DbSet<>.
I have some extension methods written for this, but have distilled the problem down into a single test.
I thought in Moq if you Setup the same call with the same parameters (filter), the Setup is replaced?
But, yet, this below unit test shows that it is added?
See 'below throws "Expected collection to contain 1 item(s), but found 2."'
[Fact] public void Add2Test() { var contextMock = new Mock<IDbContext>(); List<MyEntity> data = new List<MyEntity>(){new MyEntity()}; var queryable = data.AsQueryable(); var mockDbSet = new Mock<DbSet<MyEntity>>(); mockDbSet.As<IQueryable<MyEntity>>().Setup(m => m.Provider).Returns(queryable.Provider); mockDbSet.As<IQueryable<MyEntity>>().Setup(m => m.Expression).Returns(queryable.Expression); mockDbSet.As<IQueryable<MyEntity>>().Setup(m => m.ElementType).Returns(queryable.ElementType); mockDbSet.As<IQueryable<MyEntity>>().Setup(m => m.GetEnumerator()).Returns(queryable.GetEnumerator()); contextMock.Setups.Where(s => s.Expression.ReturnType == typeof(DbSet<MyEntity>)).Should().HaveCount(0); contextMock.Setup(x => x.Set<MyEntity>()).Returns(mockDbSet.Object); contextMock.Setups.Where(s => s.Expression.ReturnType == typeof(DbSet<MyEntity>)).Should().HaveCount(1); // let's do it again data = new List<MyEntity>() { new MyEntity() }; queryable = data.AsQueryable(); mockDbSet = new Mock<DbSet<MyEntity>>(); mockDbSet.As<IQueryable<MyEntity>>().Setup(m => m.Provider).Returns(queryable.Provider); mockDbSet.As<IQueryable<MyEntity>>().Setup(m => m.Expression).Returns(queryable.Expression); mockDbSet.As<IQueryable<MyEntity>>().Setup(m => m.ElementType).Returns(queryable.ElementType); mockDbSet.As<IQueryable<MyEntity>>().Setup(m => m.GetEnumerator()).Returns(queryable.GetEnumerator()); contextMock.Setups.Where(s => s.Expression.ReturnType == typeof(DbSet<MyEntity>)).Should().HaveCount(1); contextMock.Setup(x => x.Set<MyEntity>()).Returns(mockDbSet.Object); // below throws "Expected collection to contain 1 item(s), but found 2." contextMock.Setups.Where(s => s.Expression.ReturnType == typeof(DbSet<MyEntity>)).Should().HaveCount(1); }
https://stackoverflow.com/questions/65539840/moq-setup-adding-with-same-filter-instead-of-overwriting January 02, 2021 at 09:54PM
没有评论:
发表评论