示例#1
0
        public async Task AddAsyncAddsElement()
        {
            // Arrange
            var films = new List <Film>
            {
                new Film {
                    Rating = 2
                },
                new Film {
                    Rating = 3
                }
            }.AsQueryable();

            var mockSet = new Mock <DbSet <Film> >();

            mockSet.As <IQueryable <Film> >().Setup(m => m.Provider).Returns(films.Provider);
            mockSet.As <IQueryable <Film> >().Setup(m => m.Expression).Returns(films.Expression);
            mockSet.As <IQueryable <Film> >().Setup(m => m.ElementType).Returns(films.ElementType);
            mockSet.As <IQueryable <Film> >().Setup(m => m.GetEnumerator()).Returns(films.GetEnumerator());

            var film = new Film();

            var mockContext = new Mock <CinemaDbContext>();

            mockContext.Setup(c => c.Films).Returns(mockSet.Object);
            mockContext.Setup(m => m.AddAsync(It.IsAny <Film>(), It.IsAny <CancellationToken>()))
            .Returns(new ValueTask <EntityEntry <Film> >(Task.FromResult((EntityEntry <Film>)null)));

            var filmBusiness = new FilmBusiness(mockContext.Object);

            // Act
            await filmBusiness.AddAsync(film);

            // Assert
            mockSet.Verify(m => m.AddAsync(It.IsAny <Film>(), It.IsAny <CancellationToken>()), Times.Once());
            mockContext.Verify(m => m.SaveChangesAsync(It.IsAny <CancellationToken>()), Times.Once());
        }