示例#1
0
        public async Task CountAsync_ForMultipleEntries_CountAsExpected()
        {
            var playlists = new[]
            {
                new PlaylistBuilder().WithId(GuidFactory.MakeFromInt(0)).Build(),
                new PlaylistBuilder().WithId(GuidFactory.MakeFromInt(1)).Build(),
            };

            var dbContextMock = new DbContextMock <ApplicationDbContext>(DummyDbOptions);

            dbContextMock.CreateDbSetMock(x => x.PlaylistEntries, playlists);

            var sut = new PlaylistEntriesRepository(dbContextMock.Object);

            var actual = await sut.CountAsync(CancellationToken.None);

            actual.Should().Be(2);
        }
示例#2
0
        public void Register_WhenUserPasswordProvided_ReturnsRegisteredUser()
        {
            //Given
            var    passwordSalt = GetRandomByteArray();
            string password     = "******";

            byte[] passwordHash;
            using (var hmac = new System.Security.Cryptography.HMACSHA512(passwordSalt))
            {
                passwordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
            }

            var users = new List <User> {
                new User {
                    Id           = 1,
                    Username     = "******",
                    PasswordHash = GetRandomByteArray(),
                    PasswordSalt = GetRandomByteArray()
                },
                new User {
                    Id           = 2,
                    Username     = "******",
                    PasswordHash = GetRandomByteArray(),
                    PasswordSalt = GetRandomByteArray()
                }
            };

            var newUser = new User
            {
                Username = "******"
            };

            var            dbContextMock  = new DbContextMock <DataContext>(DummyOptions);
            var            usersDbSetMock = dbContextMock.CreateDbSetMock(x => x.Users, users);
            AuthRepository _sut           = new AuthRepository(dbContextMock.Object);

            //When
            var actual = _sut.Register(newUser, "password");

            var count = dbContextMock.Object.Users.Count();

            //Then
            count.Should().Be(3);
        }
示例#3
0
        public async Task GetRangeAsync_ReturnsExpectedNbOfElemnets()
        {
            var audios = new[]
            {
                new AudioBuilder().WithId(GuidFactory.MakeFromInt(0)).Build(),
                new AudioBuilder().WithId(GuidFactory.MakeFromInt(1)).Build(),
                new AudioBuilder().WithId(GuidFactory.MakeFromInt(2)).Build(),
                new AudioBuilder().WithId(GuidFactory.MakeFromInt(3)).Build(),
            };

            var dbContextMock         = new DbContextMock <ApplicationDbContext>(DummyDbOptions);
            var audioEntriesDbSetMock = dbContextMock.CreateDbSetMock(x => x.AudioEntries, audios);

            var sut = new SqlAudioEntriesRepository(dbContextMock.Object);

            var actual = await sut.GetRangeAsync(1, 2, CancellationToken.None);

            actual.Should().HaveCount(2);
        }
        public async Task ListAllAsyncWithSpecification_ShouldApplySpecification()
        {
            // Arrange
            TestEntity[] entities = _fixture.CreateMany <TestEntity>(2).ToArray();

            var dbContextMock = new DbContextMock <TestDbContext>(_options);

            dbContextMock.CreateDbSetMock(x => x.TestEntities, (x, _) => (x.Id), entities);
            var repository = new ReadRepository <TestEntity, Guid>(() => dbContextMock.Object);

            var specification = new Mock <ISpecification <TestEntity> >();

            // Act
            TestEntity[] result = await repository.GetAllAsync(specification.Object);

            // Assert
            result.Should().NotBeNull();
            result.Should().BeOfType(typeof(TestEntity[]));
        }
示例#5
0
        public async Task GetByIdAsync_WithTracking_ShouldReturnEntity()
        {
            // Arrange
            TestEntity[] entities = _fixture.CreateMany <TestEntity>(2).ToArray();

            var dbContextMock = new DbContextMock <TestDbContext>(_options);

            dbContextMock.CreateDbSetMock(x => x.TestEntities, (x, _) => x.Id, entities);

            var repository = new ReadBaseRepository <TestEntity, Guid, TestDbContext>(dbContextMock.Object);

            // Act
            TestEntity result = await repository.GetById(entities[0].Id, true);

            // Assert
            result.Should()
            .NotBeNull().And
            .BeEquivalentTo(entities[0]);
        }
示例#6
0
        public static RutrackerContext GetRutrackerContext()
        {
            var options     = new DbContextOptionsBuilder <RutrackerContext>().Options;
            var contextMock = new DbContextMock <RutrackerContext>(options);

            contextMock.CreateDbSetMock(x => x.Categories, DataInitializer.GetCategories());
            contextMock.CreateDbSetMock(x => x.Subcategories, DataInitializer.GetSubcategories());
            contextMock.CreateDbSetMock(x => x.Torrents, DataInitializer.GeTorrents());
            contextMock.CreateDbSetMock(x => x.Files, DataInitializer.GetFiles());
            contextMock.CreateDbSetMock(x => x.Comments, DataInitializer.GetComments());
            contextMock.CreateDbSetMock(x => x.Likes, DataInitializer.GetLikes());

            return(contextMock.Object);
        }
示例#7
0
        public void DbContextMock_MultipleGets_ShouldReturnDataEachTime()
        {
            // Arrange
            var users = new List <User>()
            {
                new User()
                {
                    Id = Guid.NewGuid(), FullName = "Ian Kilmister"
                },
                new User()
                {
                    Id = Guid.NewGuid(), FullName = "Phil Taylor"
                },
                new User()
                {
                    Id = Guid.NewGuid(), FullName = "Eddie Clarke"
                }
            };

            var dbContextMock = new DbContextMock <TestDbContext>(Options);

            dbContextMock.CreateDbSetMock(x => x.Users, users);

            List <string> results = new List <string>();

            // Act
            for (int i = 1; i <= 100; i++)
            {
                var readUsers = dbContextMock.Object.Users;
                foreach (var user in readUsers)
                {
                    results.Add(user.FullName);
                }
            }

            // Assert
            Assert.AreEqual(300, results.Count());
            foreach (var result in results)
            {
                Assert.IsNotEmpty(result);
            }
        }
    public void Test()
    {
        var initialEntities = new[]
        {
            new User {
                Id = Guid.NewGuid(), FullName = "Eric Cartoon"
            },
            new User {
                Id = Guid.NewGuid(), FullName = "Billy Jewel"
            },
        };

        var dbContextMock  = new DbContextMock <TestDbContext>(DummyOptions);
        var usersDbSetMock = dbContextMock.CreateDbSetMock(x => x.Users, initialEntities);

        // Pass dbContextMock.Object to the class/method you want to test

        // Query dbContextMock.Object.Users to see if certain users were added or removed
        // or use Mock Verify functionality to verify if certain methods were called: usersDbSetMock.Verify(x => x.Add(...), Times.Once);
    }
        public async Task DbContextMock_CreateDbSetMock_AsyncAddMultipleModelsWithLongAsDatabaseGeneratedIdentityKey_ShouldGenerateIncrementalKey()
        {
            // Arrange
            var dbContextMock = new DbContextMock <TestDbContext>(Options);
            var dbSetMock     = dbContextMock.CreateDbSetMock(x => x.Issue20Models);

            // Act
            await dbContextMock.Object.Issue20Models.AddAsync(new Issue20Model { Url = "A" });

            await dbContextMock.Object.Issue20Models.AddAsync(new Issue20Model { Url = "B" });

            await dbContextMock.Object.Issue20Models.AddAsync(new Issue20Model { Url = "C" });

            await dbContextMock.Object.SaveChangesAsync();

            // Assert
            Assert.That(dbSetMock.Object.First(x => x.Url == "A").LoggingRepositoryId, Is.EqualTo(1));
            Assert.That(dbSetMock.Object.First(x => x.Url == "B").LoggingRepositoryId, Is.EqualTo(2));
            Assert.That(dbSetMock.Object.First(x => x.Url == "C").LoggingRepositoryId, Is.EqualTo(3));
        }
示例#10
0
        public async Task CreateBook_AddsANewBook_ToBooksTable()
        {
            //Arrange
            var moq = new DbContextMock <MyAppDbContext>(dummyOptions);

            moq.CreateDbSetMock(i => i.Books, new[]
            {
                new Book {
                    Id = 1, Title = "Animals and Nature", Author = "James X", CategoryId = 1, ISBN = 1234567890, Price = 10, DateOfPublication = "2018-03-11"
                },

                new Book {
                    Id = 2, Title = "Family and Relationships", Author = "Jerry Y", CategoryId = 2, ISBN = 8876419010, Price = 20, DateOfPublication = "2019-05-18"
                }
            });//--> now we have two books inside our Books database

            BookDTO new_book = new BookDTO()
            {
                Id = 3,

                Title = "Programming Instructions",

                Author = "John Abcd",

                CategoryId = 3,

                ISBN = 1984657201,

                Price = 50,

                DateOfPublication = "2017-01-20"
            };

            //Act
            var service = new BookService(moq.Object);

            await service.CreateBook(new_book);//add a new book to database

            //Assert
            Assert.Equal(3, moq.Object.Books.Count());
        }
        public async Task DeleteAsync_UnknownEntity_ShouldNotThrowException()
        {
            // Arrange
            TestEntity[] entities      = _fixture.CreateMany <TestEntity>(2).ToArray();
            var          dbContextMock = new DbContextMock <TestDbContext>(_options);

            dbContextMock.CreateDbSetMock(x => x.TestEntities, (x, _) => (x.Id), entities);

            var repository = new ReadWriteRepository <TestEntity, Guid>(() => dbContextMock.Object);

            // Act
            await repository.DeleteAsync(_fixture.Create <TestEntity>());

            await repository.CommitAsync();

            TestEntity[] getAll = await repository.GetAllAsync();

            // Assert
            getAll.Should().ContainEquivalentOf(entities[0]);
            getAll.Should().HaveCount(2);
        }
        public async Task DeleteByIdAsync_KnownEntity_ShouldDeleteEntity()
        {
            // Arrange
            TestEntity[] entities = _fixture.CreateMany <TestEntity>(2).ToArray();

            var dbContextMock = new DbContextMock <TestDbContext>(_options);

            dbContextMock.CreateDbSetMock(x => x.TestEntities, (x, _) => (x.Id), entities);
            var repository = new ReadWriteRepository <TestEntity, Guid>(() => dbContextMock.Object);

            // Act
            await repository.DeleteByIdAsync(entities[0].Id);

            await repository.CommitAsync();

            TestEntity[] getAll = await repository.GetAllAsync();

            // Assert
            getAll.SingleOrDefault(x => x.Id == entities[0].Id).Should().BeNull();
            getAll.Should().HaveCount(1);
        }
        public void GetMyCart_WhenCalled_ReturnsAllCartItems()
        {
            //Arrange
            var myDbContextMoq = new DbContextMock <ShoppingCartContext>(myDummyOptions);

            CartItem my_CartItem1 = new CartItem()
            {
                ProductId = 1,
                Price     = 3,
                Quantity  = 2
            };

            CartItem my_CartItem2 = new CartItem()
            {
                ProductId = 2,
                Price     = 2,
                Quantity  = 5
            };

            List <CartItem> All_Cart_Items = new List <CartItem>();

            All_Cart_Items.Add(my_CartItem1);
            All_Cart_Items.Add(my_CartItem2);

            myDbContextMoq.CreateDbSetMock(x => x.Carts, new[]
            {
                new Cart {
                    CartId = 1, CartName = "My Cart", AllCartItems = All_Cart_Items, GrandTotal = 16
                }
            });

            //Pass myDbContextMoq.Object to the CartService class
            CartService service = new CartService(myDbContextMoq.Object);

            //Act
            var result = service.GetMyCart();//Call GetMyCart() function

            //Assert
            Assert.NotNull(result);
        }
示例#14
0
 public virtual void Setup()
 {
     _data = new List <User>
     {
         new User
         {
             Id              = 1,
             FirstName       = "AAA",
             LastName        = "AAA",
             SuccessfulTrips = 1,
             Type            = UserType.Driver,
             Password        = "******",
             Email           = "*****@*****.**"
         },
         new User
         {
             Id              = 2,
             FirstName       = "BBB",
             LastName        = "BBB",
             SuccessfulTrips = 1,
             Type            = UserType.Driver,
             Password        = "******",
             Email           = "*****@*****.**"
         },
         new User
         {
             Id              = 3,
             FirstName       = "CCC",
             LastName        = "CCC",
             SuccessfulTrips = 1,
             Type            = UserType.Driver,
             Password        = "******",
             Email           = "*****@*****.**"
         }
     };
     _contextMock = new DbContextMock <TaxiContext>("defaultconnection");
     _mockSet     = _contextMock.CreateDbSetMock(i => i.Users, _data);
     _contextMock.Setup(i => i.Users).Returns(_mockSet.Object);
 }
示例#15
0
        public async Task ListAllAsyncWithSpecification_ShouldApplySpecification()
        {
            // Arrange
            TestEntity[] entities = _fixture.CreateMany <TestEntity>(2).ToArray();

            var dbContextMock = new DbContextMock <TestDbContext>(_options);

            dbContextMock.CreateDbSetMock(x => x.TestEntities, (x, _) => x.Id, entities);
            dbContextMock.Setup(s => s.Set <TestEntity>().AsQueryable()).Returns(entities.AsQueryable());
            var repository = new ReadBaseRepository <TestEntity, Guid, TestDbContext>(dbContextMock.Object);

            var specification = new Mock <ISpecification <TestEntity> >();

            // Act
            TestEntity[] result = await repository.GetAll(specification.Object);

            // Assert
            result.Should()
            .NotBeEmpty().And
            .BeOfType(typeof(TestEntity[])).And
            .BeEquivalentTo(entities);
        }
示例#16
0
        public void Login_GivenCredentials_WhenCorrect_ReturnsUser()
        {
            //Given
            var    passwordSalt = GetRandomByteArray();
            string password     = "******";

            byte[] passwordHash;
            using (var hmac = new System.Security.Cryptography.HMACSHA512(passwordSalt))
            {
                passwordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
            }

            var users = new List <User> {
                new User {
                    Id           = 1,
                    Username     = "******",
                    PasswordHash = passwordHash,
                    PasswordSalt = passwordSalt
                },
                new User {
                    Id           = 2,
                    Username     = "******",
                    PasswordHash = GetRandomByteArray(),
                    PasswordSalt = GetRandomByteArray()
                }
            };

            var            dbContextMock  = new DbContextMock <DataContext>(DummyOptions);
            var            usersDbSetMock = dbContextMock.CreateDbSetMock(x => x.Users, users);
            AuthRepository _sut           = new AuthRepository(dbContextMock.Object);

            //When
            var actual       = _sut.Login("admin", "password");
            var expectedUser = users.FirstOrDefault(u => u.Username == "admin");
            var actualUser   = actual.Result;

            //Then
            actualUser.Should().BeEquivalentTo(expectedUser);
        }
示例#17
0
        public void TestStatisticService()
        {
            //Arrange
            var mockDbContext = new DbContextMock <GameContext>("hhh");
            var mockDbSet     = mockDbContext.CreateDbSetMock(x => x.GameScores, _gameScoreDb);


            //Act
            var statServ  = new StatisticService(mockDbContext.Object);
            var actual    = statServ.LoadGameScoreStatistic();
            var actualSel = _gameScoreDb.Select(s => new GameScore {
                Name = s.Name, CountWin = s.CountWin
            }).ToList();

            // var actualAny = actualSel.Except<GameScore>(actual, new GameScoreComparer());//.DefaultIfEmpty()..Any()

            //Assert
            Assert.IsTrue(actualSel.SequenceEqual(actual, new GameScoreComparer()));
            Assert.IsFalse(actualSel.Except <GameScore>(actual, new GameScoreComparer()).Any());//.DefaultIfEmpty()
            Assert.IsTrue(actual.Count() == 3);
            Assert.IsTrue(actualSel.Count() == 3);
        }
        public void Test()
        {
            #region Arrange

            var dbContextMock = new DbContextMock <FakeContext>();

            var mockSetGuild = dbContextMock.CreateDbSetMock(x => x.Guilds, GetTestGuilds());

            CancellationTokenSource source = new CancellationTokenSource();
            CancellationToken       token  = source.Token;
            var mock = new Mock <FakeContext>();
            mock.Setup(c => c.Guilds).Returns(mockSetGuild.Object);

            SaveChangesInFakeContext(mock, token, SaveFakeDbSets, mockSetGuild);

            var services = new ServiceCollection()
                           .AddScoped <IEFContext>(provider => mock.Object)
                           .BuildServiceProvider();

            var wordSearchesService = new WordSearchService(services);
            var searchText          = "Test";
            var reply = "Test passed";
            #endregion

            #region Act
            wordSearchesService.AddSearchWord(1, reply, searchText);
            var answer     = wordSearchesService.SearchWord(1, searchText);
            var nullAnswer = wordSearchesService.SearchWord(1, "randomtexthere");
            #endregion

            #region Assert
            Assert.NotNull(answer);
            Assert.Equal(answer, reply);
            Assert.Null(nullAnswer);
            #endregion

            SetTestOutput("WordSearchService test passed");
        }
        public async Task CreateCategory_AddsNewCategory_ToCategoriesTable()
        {
            //Arrange
            var context_Moq = new DbContextMock <MyAppDbContext>(dummyOptions);

            context_Moq.CreateDbSetMock(i => i.Categories, new[]
            {
                new Category {
                    CategoryId = 1, CategoryName = "Fiction"
                },

                new Category {
                    CategoryId = 2, CategoryName = "Romance"
                },

                new Category {
                    CategoryId = 3, CategoryName = "Fantasy"
                }
            });//--> now we have three categories inside our Categories database

            //We want to add a new Category (i.e the following) to our database
            var my_new_category = new CategoryDTO()
            {
                CategoryId = 4,

                CategoryName = "Sports"
            };

            //Act
            var my_service = new CategoryService(context_Moq.Object);

            await my_service.CreateCategory(my_new_category);

            //Assert
            //We have 3 Categories inside our Categories table
            //When we add a new Category to Categoires table then the size of Categories table increases by 1
            Assert.Equal(4, context_Moq.Object.Categories.Count());
        }
        public void DotaAssistansTest()
        {
            #region Arrange
            var dbContextMock = new DbContextMock <FakeContext>();

            var mockSet = dbContextMock.CreateDbSetMock(x => x.Cooldowns, GetTestCooldowns());

            CancellationTokenSource source = new CancellationTokenSource();
            CancellationToken       token  = source.Token;
            var mock = new Mock <FakeContext>();
            mock.Setup(c => c.Cooldowns).Returns(mockSet.Object);

            var services = new ServiceCollection()
                           .AddScoped <IEFContext>(provider => mock.Object)
                           .AddSingleton <ILogger, LoggerEmptyService>()
                           .BuildServiceProvider();

            SaveChangesInFakeContext(mock, token, SaveFakeDbSets, mockSet);

            var cooldownService = new CooldownService(services);
            #endregion

            #region Act
            bool firstCheck = cooldownService.Check("test");
            cooldownService.Set("test");
            bool secondCheck = cooldownService.Check("test");
            Thread.Sleep(5000);
            bool thirdCheck = cooldownService.Check("test");
            #endregion

            #region Assert
            Assert.True(firstCheck);
            Assert.False(secondCheck);
            Assert.True(firstCheck);
            #endregion

            SetTestOutput("Cooldown Service test passed");
        }
示例#21
0
        public void DbContextMock_CreateDbSetMock_AddMultipleModelsWithLongAsDatabaseGeneratedIdentityKey_ShouldGenerateIncrementalKey()
        {
            // Arrange
            var dbContextMock = new DbContextMock <TestDbContext>("abc");
            var dbSetMock     = dbContextMock.CreateDbSetMock(x => x.IntKeyModels);

            // Act
            dbContextMock.Object.IntKeyModels.Add(new IntKeyModel {
                Url = "A"
            });
            dbContextMock.Object.IntKeyModels.Add(new IntKeyModel {
                Url = "B"
            });
            dbContextMock.Object.IntKeyModels.Add(new IntKeyModel {
                Url = "C"
            });
            dbContextMock.Object.SaveChanges();

            // Assert
            Assert.That(dbSetMock.Object.First(x => x.Url == "A").LoggingRepositoryId, Is.EqualTo(1));
            Assert.That(dbSetMock.Object.First(x => x.Url == "B").LoggingRepositoryId, Is.EqualTo(2));
            Assert.That(dbSetMock.Object.First(x => x.Url == "C").LoggingRepositoryId, Is.EqualTo(3));
        }
        public async Task RemoveCategory_DeletesCategory_FromDatabase()
        {
            //Arrange
            var context_Moq = new DbContextMock <MyAppDbContext>(dummyOptions);

            context_Moq.CreateDbSetMock(i => i.Categories, new[]
            {
                new Category {
                    CategoryId = 1, CategoryName = "Fiction"
                },

                new Category {
                    CategoryId = 2, CategoryName = "Romance"
                },

                new Category {
                    CategoryId = 3, CategoryName = "Journal"
                },                                                      //--> we want to remove this

                new Category {
                    CategoryId = 4, CategoryName = "Sports"
                },

                new Category {
                    CategoryId = 5, CategoryName = "Family"
                },
            });

            //Act
            var service = new CategoryService(context_Moq.Object);

            await service.RemoveCategory(3);

            //Assert
            //When we remove one Category then the size will decrease by one
            Assert.Equal(4, context_Moq.Object.Categories.Count());
        }
        public async Task UpdateProduct_EditsTheProduct_AndAddsTheUpdatedProductToProductsTable()
        {
            //Arrange
            var myDbContextMoq = new DbContextMock <ShoppingCartContext>(myDummyOptions);

            //Create list of Products that contains only two Products : "Milk" and "Oranges"
            myDbContextMoq.CreateDbSetMock(x => x.Products, new[]
            {
                new Product {
                    ProductId = 1, ProductName = "Milk", Price = 3, CategoryId = 1
                },
                new Product {
                    ProductId = 2, ProductName = "Oranges", Price = 2, CategoryId = 2
                },
            });


            ProductDTO testDataDTO = new ProductDTO()
            {
                ProductId   = 1,
                ProductName = "Modified Name",
                Price       = 3,
                CategoryId  = 1
            };

            ProductService service = new ProductService(myDbContextMoq.Object);

            //Act
            //for example we want to update the Product "Milk"
            await service.UpdateProduct(testDataDTO);

            Product productToBeUpdated = myDbContextMoq.Object.Products.FirstOrDefault(x => x.ProductId == 1);

            //Assert
            //ProductName changed from "Milk" to "Modified Name"
            Assert.Equal("Modified Name", productToBeUpdated.ProductName);
        }
        public async Task DbContextMock_CreateDbSetMock_PassInitialEntities_DbSetShouldContainInitialEntities()
        {
            var dbContextMock = new DbContextMock <TestDbContext>(Options);

            dbContextMock.CreateDbSetMock(x => x.Users, new[]
            {
                new User {
                    Id = Guid.NewGuid(), FullName = "Eric Cartoon"
                },
                new User {
                    Id = Guid.NewGuid(), FullName = "Billy Jewel"
                },
            });

            Assert.That(dbContextMock.Object.Users.Count(), Is.EqualTo(2));
            Assert.That(await dbContextMock.Object.Users.CountAsync(), Is.EqualTo(2));

            var result = await dbContextMock.Object.Users.FirstAsync(x => x.FullName.StartsWith("Eric"));

            Assert.That(result.FullName, Is.EqualTo("Eric Cartoon"));

            result = dbContextMock.Object.Users.First(x => x.FullName.Contains("Jewel"));
            Assert.That(result.FullName, Is.EqualTo("Billy Jewel"));
        }
        public void DbContextMock_CreateDbSetMock_AddMultipleModelsWithGuidAsDatabaseGeneratedIdentityKey_ShouldGenerateRandomGuidAsKey()
        {
            var knownId       = Guid.NewGuid();
            var dbContextMock = new DbContextMock <TestDbContext>(Options);
            var dbSetMock     = dbContextMock.CreateDbSetMock(x => x.GeneratedGuidKeyModels, new[]
            {
                new GeneratedGuidKeyModel {
                    Id = knownId, Value = "first"
                },
                new GeneratedGuidKeyModel {
                    Value = "second"
                }
            });

            dbSetMock.Object.Add(new GeneratedGuidKeyModel {
                Value = "third"
            });
            dbContextMock.Object.SaveChanges();

            var modelWithKnownId = dbSetMock.Object.FirstOrDefault(x => x.Id == knownId);

            Assert.That(modelWithKnownId, Is.Not.Null);
            Assert.That(modelWithKnownId.Value, Is.EqualTo("first"));
        }
        public void DbContextMock_CreateDbSetMock_AddMultipleModelsWithDatabaseGeneratedIdentityKey_ShouldGenerateSequentialKey()
        {
            var dbContextMock = new DbContextMock <TestDbContext>(Options);
            var dbSetMock     = dbContextMock.CreateDbSetMock(x => x.GeneratedKeyModels, new[]
            {
                new GeneratedKeyModel {
                    Value = "first"
                },
                new GeneratedKeyModel {
                    Value = "second"
                }
            });

            dbSetMock.Object.Add(new GeneratedKeyModel {
                Value = "third"
            });
            dbContextMock.Object.SaveChanges();

            Assert.That(dbSetMock.Object.Min(x => x.Id), Is.EqualTo(1));
            Assert.That(dbSetMock.Object.Max(x => x.Id), Is.EqualTo(3));
            Assert.That(dbSetMock.Object.First(x => x.Id == 1).Value, Is.EqualTo("first"));
            Assert.That(dbSetMock.Object.First(x => x.Id == 2).Value, Is.EqualTo("second"));
            Assert.That(dbSetMock.Object.First(x => x.Id == 3).Value, Is.EqualTo("third"));
        }
示例#27
0
        public async Task GetAllBooks_WhenCalled_ReturnsAllBooks()
        {
            //Arrange
            var moq = new DbContextMock <MyAppDbContext>(dummyOptions);

            moq.CreateDbSetMock(i => i.Books, new[]
            {
                new Book {
                    Id = 1, Title = "Animals and Nature", Author = "James X", CategoryId = 1, ISBN = 1234567890, Price = 10, DateOfPublication = "2018-03-11"
                },

                new Book {
                    Id = 2, Title = "Family and Relationships", Author = "Jerry Y", CategoryId = 2, ISBN = 8876419010, Price = 20, DateOfPublication = "2019-05-18"
                }
            });//--> now we have two books inside our Books database hence it is not null

            //Act
            var service = new BookService(moq.Object);

            await service.GetAllBooks();

            //Assert
            Assert.NotNull(moq.Object.Books);
        }
示例#28
0
        public void UserExists_WhenIncorrectUser_ReturnsFalse()
        {
            var users = new List <User> {
                new User {
                    Id       = 1,
                    Username = "******",
                },
                new User {
                    Id       = 2,
                    Username = "******",
                }
            };

            var            dbContextMock  = new DbContextMock <DataContext>(DummyOptions);
            var            usersDbSetMock = dbContextMock.CreateDbSetMock(x => x.Users, users);
            AuthRepository _sut           = new AuthRepository(dbContextMock.Object);

            //When
            var actual     = _sut.UserExists("admins");
            var actualUser = actual.Result;

            //Then
            actualUser.Should().BeFalse();
        }
        public void GetOneCartItem_WhenCalled_ReturnsOneCartItem()
        {
            //Arrange
            var context_Moq = new DbContextMock <MyAppDbContext>(dummyOptions);

            context_Moq.CreateDbSetMock(x => x.BooksAsCartItems, new[]
            {
                new BookAsCartItem {
                    Id = 1, Price = 10, Quantity = 2
                },

                new BookAsCartItem {
                    Id = 2, Price = 20, Quantity = 1
                }
            });

            //Act
            BookAsCartItemService service = new BookAsCartItemService(context_Moq.Object);

            var chosen_Item1 = context_Moq.Object.BooksAsCartItems.FirstOrDefault(i => i.Id == 1);

            var chosen_Item2 = context_Moq.Object.BooksAsCartItems.FirstOrDefault(i => i.Id == 2);

            service.GetOneCartItem(1);

            service.GetOneCartItem(2);

            //Assert
            Assert.Equal(10, chosen_Item1.Price);

            Assert.Equal(2, chosen_Item1.Quantity);

            Assert.Equal(20, chosen_Item2.Price);

            Assert.Equal(1, chosen_Item2.Quantity);
        }
        public async Task GetAllCartItems_WhenCalled_ReturnsAllCartItems()
        {
            //Arrange
            var my_Moq = new DbContextMock <MyAppDbContext>(dummyOptions);

            my_Moq.CreateDbSetMock(x => x.BooksAsCartItems, new[]
            {
                new BookAsCartItem {
                    Id = 1, Price = 10, Quantity = 2
                },

                new BookAsCartItem {
                    Id = 2, Price = 20, Quantity = 1
                }
            });

            //Act
            BookAsCartItemService my_Service = new BookAsCartItemService(my_Moq.Object);

            await my_Service.GetAllCartItems();

            //Assert
            Assert.NotNull(my_Moq.Object.BooksAsCartItems);
        }