// This is used as a 'common' test method for ActionFilterAttribute and Controller public static async Task ActionFilter_SettingResult_ShortCircuits(Mock mock) { // Arrange mock.As<IAsyncActionFilter>() .Setup(f => f.OnActionExecutionAsync( It.IsAny<ActionExecutingContext>(), It.IsAny<ActionExecutionDelegate>())) .CallBase(); mock.As<IActionFilter>() .Setup(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>())) .Callback<ActionExecutingContext>(c => { mock.ToString(); c.Result = new NoOpResult(); }); mock.As<IActionFilter>() .Setup(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>())) .Verifiable(); var context = CreateActionExecutingContext(mock.As<IFilter>().Object); var next = new ActionExecutionDelegate(() => { throw null; }); // This won't run // Act await mock.As<IAsyncActionFilter>().Object.OnActionExecutionAsync(context, next); // Assert Assert.IsType<NoOpResult>(context.Result); mock.As<IActionFilter>() .Verify(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()), Times.Never()); }
public void GetAllShouldReturnTodos() { var data = new List<Todo> { new Todo {Id = 1}, new Todo {Id = 2}, new Todo {Id = 3}, }.AsQueryable(); var mockSet = new Mock<DbSet<Todo>>(); mockSet.As<IQueryable<Todo>>().Setup(m => m.Provider).Returns(data.Provider); mockSet.As<IQueryable<Todo>>().Setup(m => m.Expression).Returns(data.Expression); mockSet.As<IQueryable<Todo>>().Setup(m => m.ElementType).Returns(data.ElementType); mockSet.As<IQueryable<Todo>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator()); var mockContext = new Mock<ApplicationDbContext>(); mockContext.Setup(c => c.Todos).Returns(mockSet.Object); var service = new TodoRepository(mockContext.Object); var todos = service.GetAll().ToList(); Assert.AreEqual(3, todos.Count); Assert.AreEqual(1, todos[0].Id); Assert.AreEqual(2, todos[1].Id); Assert.AreEqual(3, todos[2].Id); }
private legion_service_api generateSensorDataSet() { Random rnd = new Random(); IQueryable<sensor_data> data = new List<sensor_data> { new sensor_data { Id = 1, userGuid = "teste.teste.teste", sensor_name = "sensor1", timestamp = DateTime.Now.AddMilliseconds(rnd.Next(1000, 10000))}, new sensor_data { Id = 3, userGuid = "teste.teste.teste", sensor_name = "sensor2", timestamp = DateTime.Now.AddMilliseconds(rnd.Next(1000, 10000))}, new sensor_data { Id = 4, userGuid = "teste.teste.teste", sensor_name = "sensor2", timestamp = DateTime.Now.AddMilliseconds(rnd.Next(1000, 10000))}, new sensor_data { Id = 5, userGuid = "teste.teste.teste", sensor_name = "sensor3", timestamp = DateTime.Now.AddMilliseconds(rnd.Next(1000, 10000))}, new sensor_data { Id = 6, userGuid = "teste.teste.teste2", sensor_name = "sensor2", timestamp = DateTime.Now.AddMilliseconds(rnd.Next(1000, 10000))}, new sensor_data { Id = 7, userGuid = "teste.teste.teste2", sensor_name = "sensor2", timestamp = DateTime.Now.AddMilliseconds(rnd.Next(1000, 10000))}, new sensor_data { Id = 2, userGuid = "teste.teste.teste2", sensor_name = "sensor1", timestamp = DateTime.Now.AddMilliseconds(rnd.Next(1000, 10000))} }.AsQueryable(); var mockset = new Mock<DbSet<sensor_data>>(); mockset.As<IQueryable<sensor_data>>().Setup(m => m.Provider).Returns(data.Provider); mockset.As<IQueryable<sensor_data>>().Setup(m => m.Expression).Returns(data.Expression); mockset.As<IQueryable<sensor_data>>().Setup(m => m.ElementType).Returns(data.ElementType); mockset.As<IQueryable<sensor_data>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator()); var mockContext = new Mock<legion_serviceContext>(); mockContext.Setup(s => s.sensor_data).Returns(mockset.Object); return new legion_service_api(mockContext.Object); }
public void Animal_needs_an_enclosure() { var mockContext = new Mock<IZooDbContext>(); var animals = new List<Animal> { new Animal { Id = 1, Name = "Pumba", Enclosure = new Enclosure { Id = 1, Name = "Kenya Room", Location = "Center", Environment = "Africa" } } }.AsQueryable(); var mockSet = new Mock<DbSet<Animal>>(); mockSet.As<IQueryable<Animal>>().Setup(m => m.Provider).Returns(animals.Provider); mockSet.As<IQueryable<Animal>>().Setup(m => m.Expression).Returns(animals.Expression); mockSet.As<IQueryable<Animal>>().Setup(m => m.ElementType).Returns(animals.ElementType); mockSet.As<IQueryable<Animal>>().Setup(m => m.GetEnumerator()).Returns(animals.GetEnumerator()); mockContext.Setup(x => x.Animals) .Returns(mockSet.Object); var db = mockContext.Object; var controller = new HomeController() { Database = db }; var result = controller.Index(); Assert.IsType<ViewResult>(result); }
/// <summary> /// Tests patient and appointment lists. /// </summary> /// <param name="appts">List of appointments to substitute in our mockup.</param> /// <param name="patients">List of patients to substitute in our mockup.</param> /// <param name="compare_date">The date to compare in our mockup.</param> /// <returns></returns> private static IEnumerable<Transaction> TestPatientsAndAppointments( List<appointment_data> appts, List<patient_data> patients, DateTime compare_date) { var mock_appts = new Mock<DbSet<appointment_data>>(); mock_appts.As<IQueryable<appointment_data>>().Setup(m => m.Provider) .Returns(appts.AsQueryable<appointment_data>().Provider); mock_appts.As<IQueryable<appointment_data>>().Setup(m => m.Expression) .Returns(appts.AsQueryable<appointment_data>().Expression); mock_appts.As<IQueryable<appointment_data>>().Setup(m => m.ElementType) .Returns(appts.AsQueryable<appointment_data>().ElementType); mock_appts.As<IQueryable<appointment_data>>().Setup(m => m.GetEnumerator()) .Returns(appts.AsQueryable<appointment_data>().GetEnumerator()); var mock_patients = new Mock<DbSet<patient_data>>(); mock_patients.As<IQueryable<patient_data>>().Setup(m => m.Provider) .Returns(patients.AsQueryable<patient_data>().Provider); mock_patients.As<IQueryable<patient_data>>().Setup(m => m.Expression) .Returns(patients.AsQueryable<patient_data>().Expression); mock_patients.As<IQueryable<patient_data>>().Setup(m => m.ElementType) .Returns(patients.AsQueryable<patient_data>().ElementType); mock_patients.As<IQueryable<patient_data>>().Setup(m => m.GetEnumerator()) .Returns(patients.AsQueryable<patient_data>().GetEnumerator()); var fake_entities = new Mock<broadlyEntities>(); fake_entities.Setup(c => c.appointment_data).Returns(mock_appts.Object); fake_entities.Setup(c => c.patient_data).Returns(mock_patients.Object); IEnumerable<Transaction> transactions = DataSource.GetTransactions(compare_date, fake_entities.Object); Assert.IsNotNull(transactions); Assert.IsTrue(transactions is IQueryable); Assert.IsTrue(transactions is IQueryable<Transaction>); foreach (Transaction transaction in transactions) { // There is an email Assert.IsTrue(!string.IsNullOrEmpty(transaction.PatientEmail)); // The appoinment time matches Assert.IsTrue(transaction.AppointmentTime == compare_date); // There is a transaction with this Id appointment_data appt = appts.Find(x => x.appointment_id == transaction.AppointmentId); Assert.IsNotNull(appt); // There is a patient with the appt's Id patient_data patient = patients.Find(x => x.patient_id == appt.patient_id); Assert.IsNotNull(patient); // Check content Assert.IsTrue(transaction.AppointmentId == appt.appointment_id); Assert.IsTrue(transaction.AppointmentTime == appt.scheduled); Assert.IsTrue(appt.status == "completed"); Assert.IsTrue(transaction.PatientFirstName == patient.first_name); Assert.IsTrue(transaction.PatientLastName == patient.last_name); Assert.IsTrue(transaction.PatientId == patient.patient_id); Assert.IsTrue(transaction.PatientPhone == patient.phone); } return transactions; }
public void GetAllTasks_Order_By_Username() { var taskData = new List<TaskModel> { Build_Task_For_Testing("B's Task", new DateTime(2015, 7, 3, 5, 5, 5), "B's Test Task", "B"), Build_Task_For_Testing("C's Task", new DateTime(2015, 7, 5, 5, 5, 5), "C's Test Task", "C"), Build_Task_For_Testing("D's Task", new DateTime(2015, 7, 6, 5, 5, 5), "D's Test Task", "D") }.AsQueryable(); var taskData2 = new List<TaskModel> { }.AsQueryable(); var mockSet = new Mock<DbSet<TaskModel>>(); mockSet.As<IQueryable<TaskModel>>().Setup(m => m.Provider).Returns(taskData.Provider); mockSet.As<IQueryable<TaskModel>>().Setup(m => m.Expression).Returns(taskData.Expression); mockSet.As<IQueryable<TaskModel>>().Setup(m => m.ElementType).Returns(taskData.ElementType); mockSet.As<IQueryable<TaskModel>>().Setup(m => m.GetEnumerator()).Returns(taskData.GetEnumerator()); var mockDbContext = new Mock<TaskDBContext>(); mockDbContext.Setup(t => t.Tasks).Returns(mockSet.Object); var testClass = new TestClass(mockDbContext.Object); var allTasks = testClass.GetAllTasks(); Assert.AreEqual(3, allTasks.Count); Assert.AreEqual("B", allTasks[0].Username); Assert.AreEqual("C", allTasks[1].Username); Assert.AreEqual("D", allTasks[2].Username); }
public void testIndesReturnsAViewForTheRelevantProductID() { var Products = new List<Product> { new Product{ID = 1,Title = "FirstProduct",Description = "First Product In Database"} }.AsQueryable(); Mock<IHypermartContext> mockDBContext = new Mock<IHypermartContext>(); var mockSet = new Mock<DbSet<Product>>(); mockSet.As<IQueryable<Product>>().Setup(m => m.Provider).Returns(Products.Provider); mockSet.As<IQueryable<Product>>().Setup(m => m.Expression).Returns(Products.Expression); mockSet.As<IQueryable<Product>>().Setup(m => m.ElementType).Returns(Products.ElementType); mockSet.As<IQueryable<Product>>().Setup(m => m.GetEnumerator()).Returns(Products.GetEnumerator()); mockDBContext.Setup(x => x.Products).Returns(mockSet.Object); var xy = mockDBContext.Object.Products.ToList(); ProductsController SUT = new ProductsController(mockDBContext.Object); ActionResult ViewResults =SUT.Index(); ViewResult vResult = ViewResults as ViewResult; if (vResult != null) { Assert.AreEqual(string.Empty, vResult.ViewName); //Assert.IsInstanceOfType(typeof(Product),vResult.Model.GetType() ); //Product model = vResult.Model as Product; //if (model != null) //{ // //... //} } }
public void AssemblyStatusService_GetAsync_ReturnsAssemblyStatussByIds() { //Arrange var mockDbContextScopeFac = new Mock<IDbContextScopeFactory>(); var mockDbContextScope = new Mock<IDbContextReadOnlyScope>(); var mockEfDbContext = new Mock<EFDbContext>(); mockDbContextScopeFac.Setup(x => x.CreateReadOnly(DbContextScopeOption.JoinExisting)).Returns(mockDbContextScope.Object); mockDbContextScope.Setup(x => x.DbContexts.Get<EFDbContext>()).Returns(mockEfDbContext.Object); var dbEntry1 = new AssemblyStatus { Id = "dummyEntryId1", AssyStatusName = "Name1", AssyStatusAltName = "NameAlt1", IsActive_bl = false }; var dbEntry2 = new AssemblyStatus { Id = "dummyEntryId2", AssyStatusName = "Name2", AssyStatusAltName = "NameAlt2", IsActive_bl = true }; var dbEntry3 = new AssemblyStatus { Id = "dummyEntryId3", AssyStatusName = "Name3", AssyStatusAltName = "NameAlt3", IsActive_bl = true }; var dbEntries = (new List<AssemblyStatus> { dbEntry1, dbEntry2, dbEntry3 }).AsQueryable(); var mockDbSet = new Mock<DbSet<AssemblyStatus>>(); mockDbSet.As<IDbAsyncEnumerable<AssemblyStatus>>().Setup(m => m.GetAsyncEnumerator()).Returns(new MockDbAsyncEnumerator<AssemblyStatus>(dbEntries.GetEnumerator())); mockDbSet.As<IQueryable<AssemblyStatus>>().Setup(m => m.Provider).Returns(new MockDbAsyncQueryProvider<AssemblyStatus>(dbEntries.Provider)); mockDbSet.As<IQueryable<AssemblyStatus>>().Setup(m => m.Expression).Returns(dbEntries.Expression); mockDbSet.As<IQueryable<AssemblyStatus>>().Setup(m => m.ElementType).Returns(dbEntries.ElementType); mockDbSet.As<IQueryable<AssemblyStatus>>().Setup(m => m.GetEnumerator()).Returns(dbEntries.GetEnumerator()); mockDbSet.Setup(x => x.Include(It.IsAny<string>())).Returns(mockDbSet.Object); mockEfDbContext.Setup(x => x.AssemblyStatuss).Returns(mockDbSet.Object); var assyStatusService = new AssemblyStatusService(mockDbContextScopeFac.Object, "dummyUserId"); //Act var serviceResult = assyStatusService.GetAsync(new string[] { "dummyEntryId3" }).Result; //Assert Assert.IsTrue(serviceResult.Count == 1); Assert.IsTrue(serviceResult[0].AssyStatusAltName.Contains("NameAlt3")); }
public void ClassInit() { // Installing mock DbSet. var data = new List<MockCatalog> { new MockCatalog(false) { Name = "BBB" }, new MockCatalog(false) { Name = "ZZZ" }, new MockCatalog(false) { Name = "AAA" }, }.AsQueryable(); var mockDbSet = new Mock<DbSet<MockCatalog>>(); mockDbSet.As<IQueryable<MockCatalog>>().Setup(m => m.Provider).Returns(data.Provider); mockDbSet.As<IQueryable<MockCatalog>>().Setup(m => m.Expression).Returns(data.Expression); mockDbSet.As<IQueryable<MockCatalog>>().Setup(m => m.ElementType).Returns(data.ElementType); mockDbSet.As<IQueryable<MockCatalog>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator()); // Installing mock Context. var mockContext = new Mock<MetadataEFContext>(); mockContext.Setup(m => m.Set<MockCatalog>()).Returns(mockDbSet.Object); // Installing repository. var catalogRepository = new EFCatalogRepository<MockCatalog>(mockContext.Object); // Installing shared tests. SharedTests = new SharedTests<MockCatalog>(mockDbSet, mockContext, catalogRepository, CreateCatalogItem); }
public void DeberiActualizar() { var mockSet = new Mock<DbSet<Student>>(); var mockContext = new Mock<UniversityContext>(); mockContext.Setup(m => m.Students).Returns(mockSet.Object); var existing = new Student { StudentId = 1, Nombre = "Carlos", Paterno = "Estrada", Materno = "Copa", Telefono = 2269587 }; var data = new Student { StudentId = 1, Nombre = "Carlos", Paterno = "Estrada", Materno = "Copa", Telefono = 2269587, }; var queryable = new List<Student> { data }.AsQueryable(); mockSet.As<IQueryable<Student>>().Setup(m => m.Provider).Returns(queryable.Provider); mockSet.As<IQueryable<Student>>().Setup(m => m.Expression).Returns(queryable.Expression); mockSet.As<IQueryable<Student>>().Setup(m => m.ElementType).Returns(queryable.ElementType); mockSet.As<IQueryable<Student>>().Setup(m => m.GetEnumerator()).Returns(queryable.GetEnumerator()); mockContext.Setup(m => m.SaveChanges()).Verifiable(); var service = new UniversityContextService(mockContext.Object); service.UpdateStudent(data); var mostrar = service.Show(); mockContext.Verify(); Assert.AreEqual(1, mostrar.Count); Assert.AreEqual("Carlos", mostrar[0].Nombre); Assert.AreEqual(2269587, mostrar[0].Telefono); }
public void Handler_ReturnsFalse_WhenUserExists_ButHasDifferentPassword() { string nameOrVerifiedEmail = FakeData.Email(); string password = FakeData.String(); var user = new User { Name = nameOrVerifiedEmail, }; var queries = new Mock<IProcessQueries>(MockBehavior.Strict); Expression<Func<UserByNameOrVerifiedEmail, bool>> expectedQuery = x => x.NameOrEmail == nameOrVerifiedEmail; queries.Setup(x => x.Execute(It.Is(expectedQuery))) .Returns(Task.FromResult(user)); var userStore = new Mock<IUserStore<User, int>>(MockBehavior.Strict); userStore.Setup(x => x.FindByNameAsync(nameOrVerifiedEmail)).Returns(Task.FromResult(user)); var passwordHasher = new PasswordHasher(); Expression<Func<User, bool>> expectedUser = x => x.Name == nameOrVerifiedEmail; userStore.As<IUserPasswordStore<User, int>>().Setup(x => x.GetPasswordHashAsync(It.Is(expectedUser))) .Returns(Task.FromResult(passwordHasher.HashPassword(FakeData.String()))); var userManager = new UserManager<User, int>(userStore.Object); var handler = new HandleIsPasswordVerifiedQuery(queries.Object, userManager); var query = new IsPasswordVerified { UserNameOrVerifiedEmail = nameOrVerifiedEmail, Password = password, }; bool result = handler.Handle(query).Result; result.ShouldBeFalse(); queries.Verify(x => x.Execute(It.Is(expectedQuery)), Times.Once()); userStore.Verify(x => x.FindByNameAsync(nameOrVerifiedEmail), Times.Once); userStore.As<IUserPasswordStore<User, int>>().Verify( x => x.GetPasswordHashAsync(It.Is(expectedUser)), Times.Once); }
public void ReturnsPostsThatHavePublishedSetToTrue_AndPostedDateDesc() { var posts = new List<Post> { new Post {Id = 1, PostedOn = DateTime.Now.AddDays(-2), Published = true}, new Post {Id = 2, PostedOn = DateTime.Now.AddDays(-1), Published = false}, new Post {Id = 3, PostedOn = DateTime.Now, Published = true}, }.AsQueryable(); var mockPosts = new Mock<DbSet<Post>>(); mockPosts.As<IQueryable<Post>>().Setup(m => m.Provider).Returns(posts.Provider); mockPosts.As<IQueryable<Post>>().Setup(m => m.Expression).Returns(posts.Expression); mockPosts.As<IQueryable<Post>>().Setup(m => m.ElementType).Returns(posts.ElementType); mockPosts.As<IQueryable<Post>>().Setup(m => m.GetEnumerator()).Returns(posts.GetEnumerator()); var expected = mockPosts.Object.Where(x => x.Published).OrderByDescending(x => x.PostedOn).ToList(); _slapdashContext .Setup(x => x.Posts) .Returns(mockPosts.Object); var actual = _classUnderTest.Posts(1, 1); Assert.Equal(expected, actual); }
public void ComponentStatusService_GetAsync_ReturnsComponentStatuss() { //Arrange var mockDbContextScopeFac = new Mock<IDbContextScopeFactory>(); var mockDbContextScope = new Mock<IDbContextReadOnlyScope>(); var mockEfDbContext = new Mock<EFDbContext>(); mockDbContextScopeFac.Setup(x => x.CreateReadOnly(DbContextScopeOption.JoinExisting)).Returns(mockDbContextScope.Object); mockDbContextScope.Setup(x => x.DbContexts.Get<EFDbContext>()).Returns(mockEfDbContext.Object); var dbEntry1 = new ComponentStatus { Id = "dummyEntryId1", CompStatusName = "Name1", CompStatusAltName = "NameAlt1", IsActive_bl = false, Comments = "DummyComments1" }; var dbEntry2 = new ComponentStatus { Id = "dummyEntryId2", CompStatusName = "Name2", CompStatusAltName = "NameAlt2", IsActive_bl = true, Comments = "DummyComments2" }; var dbEntries = (new List<ComponentStatus> { dbEntry1, dbEntry2 }).AsQueryable(); var mockDbSet = new Mock<DbSet<ComponentStatus>>(); mockDbSet.As<IDbAsyncEnumerable<ComponentStatus>>().Setup(m => m.GetAsyncEnumerator()).Returns(new MockDbAsyncEnumerator<ComponentStatus>(dbEntries.GetEnumerator())); mockDbSet.As<IQueryable<ComponentStatus>>().Setup(m => m.Provider).Returns(new MockDbAsyncQueryProvider<ComponentStatus>(dbEntries.Provider)); mockDbSet.As<IQueryable<ComponentStatus>>().Setup(m => m.Expression).Returns(dbEntries.Expression); mockDbSet.As<IQueryable<ComponentStatus>>().Setup(m => m.ElementType).Returns(dbEntries.ElementType); mockDbSet.As<IQueryable<ComponentStatus>>().Setup(m => m.GetEnumerator()).Returns(dbEntries.GetEnumerator()); mockDbSet.Setup(x => x.Include(It.IsAny<string>())).Returns(mockDbSet.Object); mockEfDbContext.Setup(x => x.ComponentStatuss).Returns(mockDbSet.Object); var compStatusService = new ComponentStatusService(mockDbContextScopeFac.Object,"DummyUserId"); //Act var resultComponentStatuss = compStatusService.GetAsync().Result; //Assert Assert.IsTrue(resultComponentStatuss.Count == 1); Assert.IsTrue(resultComponentStatuss[0].CompStatusAltName.Contains("NameAlt2")); }
public void ProjectService_GetAsync_ReturnsProjects() { //Arrange var mockDbContextScopeFac = new Mock<IDbContextScopeFactory>(); var mockDbContextScope = new Mock<IDbContextReadOnlyScope>(); var mockEfDbContext = new Mock<EFDbContext>(); mockDbContextScopeFac.Setup(x => x.CreateReadOnly(DbContextScopeOption.JoinExisting)).Returns(mockDbContextScope.Object); mockDbContextScope.Setup(x => x.DbContexts.Get<EFDbContext>()).Returns(mockEfDbContext.Object); var dbEntry1 = new Project { Id = "dummyEntryId1", ProjectName = "Project1", ProjectAltName = "ProjectAlt1", IsActive_bl = false, ProjectCode = "CODE1" }; var dbEntry2 = new Project { Id = "dummyEntryId2", ProjectName = "Project2", ProjectAltName = "ProjectAlt2", IsActive_bl = true, ProjectCode = "CODE2" }; var dbEntries = (new List<Project> { dbEntry1, dbEntry2 }).AsQueryable(); var mockDbSet = new Mock<DbSet<Project>>(); mockDbSet.As<IDbAsyncEnumerable<Project>>().Setup(m => m.GetAsyncEnumerator()).Returns(new MockDbAsyncEnumerator<Project>(dbEntries.GetEnumerator())); mockDbSet.As<IQueryable<Project>>().Setup(m => m.Provider).Returns(new MockDbAsyncQueryProvider<Project>(dbEntries.Provider)); mockDbSet.As<IQueryable<Project>>().Setup(m => m.Expression).Returns(dbEntries.Expression); mockDbSet.As<IQueryable<Project>>().Setup(m => m.ElementType).Returns(dbEntries.ElementType); mockDbSet.As<IQueryable<Project>>().Setup(m => m.GetEnumerator()).Returns(dbEntries.GetEnumerator()); mockDbSet.Setup(x => x.Include(It.IsAny<string>())).Returns(mockDbSet.Object); mockEfDbContext.Setup(x => x.Projects).Returns(mockDbSet.Object); var projectService = new ProjectService(mockDbContextScopeFac.Object, "dummyUserId"); //Act var resultProjects = projectService.GetAsync().Result; //Assert Assert.IsTrue(resultProjects.Count == 1); Assert.IsTrue(resultProjects[0].ProjectAltName.Contains("ProjectAlt2")); }
private ODM2Entities MockDbContext() { var queryable = (new List<ProcessingLevel> { new ProcessingLevel { ProcessingLevelCode = "Draft" }, new ProcessingLevel { ProcessingLevelCode = "Provisional" }, new ProcessingLevel { ProcessingLevelCode = "Finalized" } }).AsQueryable(); var dbSet = new Mock<DbSet<ProcessingLevel>>(); dbSet.As<IQueryable<ProcessingLevel>>().Setup(m => m.Provider).Returns(queryable.Provider); dbSet.As<IQueryable<ProcessingLevel>>().Setup(m => m.Expression).Returns(queryable.Expression); dbSet.As<IQueryable<ProcessingLevel>>().Setup(m => m.ElementType).Returns(queryable.ElementType); dbSet.As<IQueryable<ProcessingLevel>>().Setup(m => m.GetEnumerator()).Returns(queryable.GetEnumerator()); var mockContext = new Mock<ODM2Entities>(); mockContext.Setup(x => x.ProcessingLevels).Returns(dbSet.Object); return mockContext.Object; }
public void RepositoryGetArtistById() { const int expectedId = 3; var expected = new Artist { Id = expectedId, Name = "WWWW", Country = "WEE", Identifier = "dfr" }; var data = new List<Artist>{ expected, new Artist{Id = 1, Name = "Ronald", Country = "ZW", Identifier = "abc", Eliases = new List<Elias>{new Elias {Id = 1, EliasName = "Ron", ArtistId = 1}}}, new Artist{Id = 2, Name = "Zebra", Country = "SA", Identifier = "bvf", Eliases = new List<Elias>{new Elias {Id = 2, EliasName = "Zeb", ArtistId = 2}}} }.AsQueryable(); var mockSet = new Mock<DbSet<Artist>>(); mockSet.As<IQueryable<Artist>>().Setup(m => m.Provider).Returns(data.Provider); mockSet.As<IQueryable<Artist>>().Setup(m => m.Expression).Returns(data.Expression); mockSet.As<IQueryable<Artist>>().Setup(m => m.ElementType).Returns(data.ElementType); mockSet.As<IQueryable<Artist>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator()); var mockContext = new Mock<BEContext>(); mockContext.Setup(m => m.Artists).Returns(mockSet.Object); mockContext.Setup(m => m.Set<Artist>()).Returns(mockSet.Object); var repo = new Repository<Artist>(mockContext.Object); var list = repo.GetArtistById(expectedId); Assert.AreEqual(1, list.Id); }
public void EnsureICanDeleteLessonTest() { //Arrange List<Lesson> my_list = new List<Lesson>(); Mock<CContext> mock_context = new Mock<CContext>(); Mock<DbSet<Teacher>> mock_teacher = new Mock<DbSet<Teacher>>(); Mock<DbSet<Student>> mock_student = new Mock<DbSet<Student>>(); Mock<DbSet<Payment>> mock_payment = new Mock<DbSet<Payment>>(); Mock<DbSet<Lesson>> mock_lesson = new Mock<DbSet<Lesson>>(); var data = my_list.AsQueryable(); mock_lesson.As<IQueryable<Lesson>>().Setup(m => m.Provider).Returns(data.Provider); mock_lesson.As<IQueryable<Lesson>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator()); mock_lesson.As<IQueryable<Lesson>>().Setup(m => m.ElementType).Returns(data.ElementType); mock_lesson.As<IQueryable<Lesson>>().Setup(m => m.Expression).Returns(data.Expression); mock_lesson.Setup(m => m.Add(It.IsAny<Lesson>())).Callback((Lesson b) => my_list.Add(b)); mock_lesson.Setup(m => m.Remove(It.IsAny<Lesson>())).Callback((Lesson b) => my_list.Remove(b)); mock_context.Setup(m => m.Lessons).Returns(mock_lesson.Object); Repository Repo = new Repository(mock_context.Object); my_list.Add(new Lesson { LessonId = 1, Title = "Private" }); //Act bool Success = Repo.DeleteLesson(1); //Assert Assert.AreEqual(0, Repo.Context.Lessons.Count()); }
public void GetFirstUnsentAddress_ShouldReturnNull_IfNoUserWithNotSentStatusExistsInDatabase() { // Arrange var stubContext = new Mock<Context>(); var stubRecipients = new List<Recipient> { new Recipient("*****@*****.**"), new Recipient("*****@*****.**"), new Recipient("*****@*****.**"), }.AsQueryable(); stubRecipients.ElementAt(0).MarkAsSent(DateTime.Now); stubRecipients.ElementAt(1).MarkAsSent(DateTime.Now); stubRecipients.ElementAt(2).MarkAsFailed("sending failed", DateTime.Now); var stubDbSet = new Mock<DbSet<Recipient>>(); stubDbSet.As<IQueryable<Recipient>>().Setup(m => m.Provider).Returns(stubRecipients.Provider); stubDbSet.As<IQueryable<Recipient>>().Setup(m => m.Expression).Returns(stubRecipients.Expression); stubDbSet.As<IQueryable<Recipient>>().Setup(m => m.ElementType).Returns(stubRecipients.ElementType); stubDbSet.As<IQueryable<Recipient>>().Setup(m => m.GetEnumerator()).Returns(stubRecipients.GetEnumerator()); stubContext.Setup(c => c.Recipients).Returns(stubDbSet.Object); // Act var repository = new Repository(stubContext.Object); var recipient = repository.GetFirstUnsentAddress(); // Assert Assert.IsNull(recipient); }
public void InitializeContext() { var elementInfo1 = Mocks.Of<IElementInfo>().First(i => i.Name == "FooElementName" && i.DisplayName == "FooElementNameDisplayName"); var element1 = new Mock<IElement>(); element1.SetupGet(e => e.Info).Returns(elementInfo1); element1.As<IAbstractElement>().SetupGet(e => e.Info).Returns(elementInfo1); element1.As<IProductElement>().SetupGet(e => e.Info).Returns(elementInfo1); var elementInfo2 = Mocks.Of<IElementInfo>().First(i => i.Name == "BarElementName" && i.DisplayName == "BarElementNameDisplayName"); var element2 = new Mock<IElement>(); element2.Setup(e => e.InstanceName).Returns("FooElement2NameDisplayName"); element2.SetupGet(e => e.Info).Returns(elementInfo2); element2.As<IAbstractElement>().SetupGet(e => e.Info).Returns(elementInfo2); element2.As<IProductElement>().SetupGet(e => e.Info).Returns(elementInfo2); var viewInfo = new Mock<IViewInfo>(); viewInfo.SetupGet(v => v.Elements).Returns(new[] { elementInfo1, elementInfo2 }); var view = new Mock<IView>(); view.SetupGet(v => v.Info).Returns(viewInfo.Object); view.SetupGet(v => v.Elements).Returns(new[] { element1.Object, element2.Object }); var productInfo = new Mock<IPatternInfo>(); productInfo.SetupGet(pi => pi.Name).Returns("FooProductName"); productInfo.SetupGet(pi => pi.Views).Returns(new[] { viewInfo.Object }); var product = new Mock<IProduct>(); product.Setup(p => p.InstanceName).Returns("TestProduct"); product.As<IProduct>().SetupGet(p => p.Info).Returns(productInfo.Object); product.As<IProductElement>().SetupGet(p => p.Info).Returns(productInfo.Object); product.SetupGet(p => p.Views).Returns(new[] { view.Object }); this.rule = new CardinalityValidationRule(); this.rule.CurrentElement = product.Object; }
public void GetFirstUnsentAddress_ShouldReturnFirstRecipientWithNotSentStatus_IfItExistsInDatabase() { // Arrange var stubContext = new Mock<Context>(); var stubRecipients = new List<Recipient> { new Recipient("*****@*****.**"), new Recipient("*****@*****.**"), new Recipient("*****@*****.**"), }.AsQueryable(); stubRecipients.First().MarkAsSent(DateTime.Now); var stubDbSet = new Mock<DbSet<Recipient>>(); stubDbSet.As<IQueryable<Recipient>>().Setup(m => m.Provider).Returns(stubRecipients.Provider); stubDbSet.As<IQueryable<Recipient>>().Setup(m => m.Expression).Returns(stubRecipients.Expression); stubDbSet.As<IQueryable<Recipient>>().Setup(m => m.ElementType).Returns(stubRecipients.ElementType); stubDbSet.As<IQueryable<Recipient>>().Setup(m => m.GetEnumerator()).Returns(stubRecipients.GetEnumerator()); stubContext.Setup(c => c.Recipients).Returns(stubDbSet.Object); // Act var repository = new Repository(stubContext.Object); var recipient = repository.GetFirstUnsentAddress(); // Assert Assert.AreEqual("*****@*****.**", recipient.Email); }
public async Task GetAllBlogsAsync_orders_by_name() { var data = new List<Blog> { new Blog { Name = "BBB" }, new Blog { Name = "ZZZ" }, new Blog { Name = "AAA" }, }.AsQueryable(); var mockSet = new Mock<DbSet<Blog>>(); mockSet.As<IDbAsyncEnumerable<Blog>>() .Setup(m => m.GetAsyncEnumerator()) .Returns(new TestDbAsyncEnumerator<Blog>(data.GetEnumerator())); mockSet.As<IQueryable<Blog>>() .Setup(m => m.Provider) .Returns(new TestDbAsyncQueryProvider<Blog>(data.Provider)); mockSet.As<IQueryable<Blog>>().Setup(m => m.Expression).Returns(data.Expression); mockSet.As<IQueryable<Blog>>().Setup(m => m.ElementType).Returns(data.ElementType); mockSet.As<IQueryable<Blog>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator()); var mockContext = new Mock<BloggingContext>(); mockContext.Setup(c => c.Blogs).Returns(mockSet.Object); var service = new BlogService(mockContext.Object); var blogs = await service.GetAllBlogsAsync(); Assert.AreEqual(3, blogs.Count); Assert.AreEqual("AAA", blogs[0].Name); Assert.AreEqual("BBB", blogs[1].Name); Assert.AreEqual("ZZZ", blogs[2].Name); }
public void TestCacheableGetAllProductsSync() { var data = new List<Product> { new Product { ProductName = "BBB"}, new Product { ProductName = "ZZZ" }, new Product { ProductName = "AAA" } }.AsQueryable(); var mockSet = new Mock<DbSet<Product>>(); mockSet.As<IQueryable<Product>>().Setup(m => m.Provider).Returns(data.Provider); mockSet.As<IQueryable<Product>>().Setup(m => m.Expression).Returns(data.Expression); mockSet.As<IQueryable<Product>>().Setup(m => m.ElementType).Returns(data.ElementType); mockSet.As<IQueryable<Product>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator()); var mockContext = new Mock<SampleContext>(); mockContext.Setup(c => c.Products).Returns(mockSet.Object); // public List<Product> GetAllProductsOrderedByName() var products = mockContext.Object.Products .OrderBy(product => product.ProductName) .Cacheable() .ToList(); Assert.AreEqual(3, products.Count); Assert.AreEqual("AAA", products[0].ProductName); Assert.AreEqual("BBB", products[1].ProductName); Assert.AreEqual("ZZZ", products[2].ProductName); }
private void SetupForGetMessages() { var list1 = new List<Message>() { new Message() { Body = "B1" }, new Message() { Body = "B2" } }.AsQueryable(); var mockMessages = new Mock<DbSet<Message>>(); mockMessages.As<IQueryable<Message>>().Setup(m => m.Provider).Returns(list1.Provider); mockMessages.As<IQueryable<Message>>().Setup(m => m.Expression).Returns(list1.Expression); mockMessages.As<IQueryable<Message>>().Setup(m => m.ElementType).Returns(list1.ElementType); mockMessages.As<IQueryable<Message>>().Setup(m => m.GetEnumerator()).Returns(list1.GetEnumerator()); var mockContext = new Mock<AppDbContext>(); mockContext.Setup(c => c.Messages).Returns(mockMessages.Object); _dbContext = mockContext.Object; }
private Mock<ApplicationDbContext> GetApplicationDbContextMock() { // single user var appUser = new ApplicationUser(); appUser.Id = "1"; var data = new List<ToDo> { new ToDo { Id = 0, Title = "Todo 1", Completed = false, User = appUser }, new ToDo { Id = 1, Title = "Todo 2", Completed = true, User = appUser }, }.AsQueryable(); var mockSet = new Mock<DbSet<ToDo>>(); mockSet.As<IDbAsyncEnumerable<ToDo>>() .Setup(m => m.GetAsyncEnumerator()) .Returns(new TestDbAsyncEnumerator<ToDo>(data.GetEnumerator())); mockSet.As<IQueryable<ToDo>>() .Setup(m => m.Provider) .Returns(new TestDbAsyncQueryProvider<ToDo>(data.Provider)); mockSet.As<IQueryable<ToDo>>().Setup(m => m.Expression).Returns(data.Expression); mockSet.As<IQueryable<ToDo>>().Setup(m => m.ElementType).Returns(data.ElementType); mockSet.As<IQueryable<ToDo>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator()); var applicationDbContext = new Mock<ApplicationDbContext>(); applicationDbContext.Setup(c => c.ToDos).Returns(mockSet.Object); return applicationDbContext; }
public void GetUserStocks_must_return_all_stocks_of_user_from_context() { var data = new List<UserStock> { new UserStock {ID = 0, Name = "DAX", User = Thread.CurrentPrincipal.Identity.GetUserName()}, new UserStock {ID = 1, Name = "NYSE", User = "******"}, new UserStock {ID = 1, Name = "NASDAQ", User = Thread.CurrentPrincipal.Identity.GetUserName()}, }.AsQueryable(); var mockSet = new Mock<DbSet<UserStock>>(); mockSet.As<IQueryable<UserStock>>().Setup(m => m.Provider).Returns(data.Provider); mockSet.As<IQueryable<UserStock>>().Setup(m => m.Expression).Returns(data.Expression); mockSet.As<IQueryable<UserStock>>().Setup(m => m.ElementType).Returns(data.ElementType); mockSet.As<IQueryable<UserStock>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator()); var mockContext = new Mock<IStockExchangeDbContext>(); mockContext.Setup(c => c.UserStocks).Returns(mockSet.Object); var service = new UserStocksController(mockContext.Object); var result = service.GetUserStocks(); Assert.AreEqual(2, result.Count()); Assert.AreEqual("DAX", result.Single(us => us.ID == 0).Name); Assert.AreEqual("NASDAQ", result.Single(us => us.ID == 1).Name); }
public async Task GetKraniumAsyncTest() { var kraniumsMockedList = new List<KraniumEntity> { new KraniumEntity { Name = "TheKranium", IPAddress = "192.168.0.50" }, //new Kranium { Name = "TheBackupKranium", IPAddress = "192.168.0.51" }, }.AsQueryable(); var mockSet = new Mock<DbSet<KraniumEntity>>(); mockSet.As<IDbAsyncEnumerable<KraniumEntity>>() .Setup(m => m.GetAsyncEnumerator()) .Returns(new TestDbAsyncEnumerator<KraniumEntity>(kraniumsMockedList.GetEnumerator())); mockSet.As<IQueryable<KraniumEntity>>() .Setup(m => m.Provider) .Returns(new TestDbAsyncQueryProvider<KraniumEntity>(kraniumsMockedList.Provider)); mockSet.As<IQueryable<KraniumEntity>>().Setup(m => m.Expression).Returns(kraniumsMockedList.Expression); mockSet.As<IQueryable<KraniumEntity>>().Setup(m => m.ElementType).Returns(kraniumsMockedList.ElementType); mockSet.As<IQueryable<KraniumEntity>>().Setup(m => m.GetEnumerator()).Returns(kraniumsMockedList.GetEnumerator()); var mockContext = new Mock<IKraniumDbContext>(); mockContext.Setup(c => c.Kranium).Returns(mockSet.Object); var repository = new EfKraniumRepository { Context = mockContext.Object }; var kranium = await repository.GetKraniumAsync(); Assert.IsNotNull(kranium); Assert.AreEqual("TheKranium", kranium.Name); Assert.AreEqual("192.168.0.50", kranium.IPAddress); }
public void PersonService_GetAsync_ReturnsPersons() { //Arrange var mockDbContextScopeFac = new Mock<IDbContextScopeFactory>(); var mockDbContextScope = new Mock<IDbContextReadOnlyScope>(); var mockEfDbContext = new Mock<EFDbContext>(); mockDbContextScopeFac.Setup(x => x.CreateReadOnly(DbContextScopeOption.JoinExisting)).Returns(mockDbContextScope.Object); mockDbContextScope.Setup(x => x.DbContexts.Get<EFDbContext>()).Returns(mockEfDbContext.Object); var mockAppUserManager = new Mock<IAppUserManager>(); var mockDbUserService = new Mock<DBUserService>(new object[] {mockDbContextScopeFac.Object, mockAppUserManager.Object, true }); var dbEntry1 = new Person { Id = "dummyEntryId1", FirstName = "First1", LastName = "Last1", IsActive_bl = false, Initials = "FLA1" }; var dbEntry2 = new Person { Id = "dummyEntryId2", FirstName = "First2", LastName = "Last2", IsActive_bl = true, Initials = "FLA2" }; var dbEntries = (new List<Person> { dbEntry1, dbEntry2 }).AsQueryable(); var mockDbSet = new Mock<DbSet<Person>>(); mockDbSet.As<IDbAsyncEnumerable<Person>>().Setup(m => m.GetAsyncEnumerator()).Returns(new MockDbAsyncEnumerator<Person>(dbEntries.GetEnumerator())); mockDbSet.As<IQueryable<Person>>().Setup(m => m.Provider).Returns(new MockDbAsyncQueryProvider<Person>(dbEntries.Provider)); mockDbSet.As<IQueryable<Person>>().Setup(m => m.Expression).Returns(dbEntries.Expression); mockDbSet.As<IQueryable<Person>>().Setup(m => m.ElementType).Returns(dbEntries.ElementType); mockDbSet.As<IQueryable<Person>>().Setup(m => m.GetEnumerator()).Returns(dbEntries.GetEnumerator()); mockEfDbContext.Setup(x => x.Persons).Returns(mockDbSet.Object); var personService = new PersonService(mockDbContextScopeFac.Object, "DummyUserId"); //Act var resultPersons = personService.GetAllAsync().Result; //Assert Assert.IsTrue(resultPersons.Count == 1); Assert.IsTrue(resultPersons[0].LastName.Contains("Last2")); }
public async Task Delete() { var data = new List<Department> { new Department {DepartmentID = 1, Name = "Test1", Budget = 1001, StartDate = DateTime.Today.AddDays(1)}, new Department {DepartmentID = 2, Name = "Test2", Budget = 1002, StartDate = DateTime.Today.AddDays(2)}, new Department {DepartmentID = 3, Name = "Test3", Budget = 1003, StartDate = DateTime.Today.AddDays(3)}, new Department {DepartmentID = 4, Name = "Test4", Budget = 1004, StartDate = DateTime.Today.AddDays(4)} }.AsQueryable(); var mockSet = new Mock<DbSet<Department>>(); mockSet.As<IQueryable<Department>>().Setup(m => m.Provider).Returns(data.Provider); mockSet.As<IQueryable<Department>>().Setup(m => m.Expression).Returns(data.Expression); mockSet.As<IQueryable<Department>>().Setup(m => m.ElementType).Returns(data.ElementType); mockSet.As<IQueryable<Department>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator()); var mockContext = new Mock<SchoolContext>(); mockContext.Setup(m => m.Departments).Returns(mockSet.Object); var controller = new DepartmentController(mockContext.Object); Department departmentToDelete = controller.GetAllDepartments().First(); await controller.Delete(departmentToDelete); mockContext.Verify(m => m.SaveChangesAsync(), Times.Once()); //Assert.AreEqual(3, controller.GetAllDepartments().Count); }
public void Index() { // DBのモックを用意する var mockset = new Mock<DbSet<BoardEntity>>(); var mockcontext = new Mock<BoardDbContext>(); var originalData = new List<BoardEntity> { new BoardEntity { Id = 1, Title = "A", Text = "a" }, new BoardEntity { Id = 2, Title = "B", Text = "b" }, new BoardEntity { Id = 3, Title = "C", Text = "c" }, }; var data = originalData.AsQueryable(); // 各メソッドの返り値をモックに差し替える mockset.As<IQueryable<BoardEntity>>().Setup( m => m.Provider ).Returns( data.Provider ); mockset.As<IQueryable<BoardEntity>>().Setup( m => m.Expression ).Returns( data.Expression ); mockset.As<IQueryable<BoardEntity>>().Setup( m => m.ElementType ).Returns( data.ElementType ); mockset.As<IQueryable<BoardEntity>>().Setup( m => m.GetEnumerator() ).Returns( data.GetEnumerator() ); mockcontext.Setup( m => m.Boards ).Returns( mockset.Object ); var controller = new BoardController( mockcontext.Object ); ViewResult result = controller.Index() as ViewResult; // モデルのデータがちゃんとDBのデータを取得出来ているか検証 var model = result.Model as BoardListModel; Assert.AreSame( originalData[0], model.Boards[0] ); Assert.AreSame( originalData[1], model.Boards[1] ); Assert.AreSame( originalData[2], model.Boards[2] ); Assert.IsNotNull( result ); }
public void CreateShouldReturnCorrectComment() { AutoMapperConfig.RegisterMappings(Assembly.Load("ForumSystem.Api")); var data = comments.AsQueryable(); var mockSet = new Mock<DbSet<Comment>>(); mockSet.As<IQueryable<Comment>>().Setup(m => m.Provider).Returns(data.Provider); mockSet.As<IQueryable<Comment>>().Setup(m => m.Expression).Returns(data.Expression); mockSet.As<IQueryable<Comment>>().Setup(m => m.ElementType).Returns(data.ElementType); mockSet.As<IQueryable<Comment>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator()); var mockContext = new Mock<IForumDbContext>(); mockContext.Setup(c => c.Comments).Returns(mockSet.Object); var controller = new CommentsController(mockContext.Object); var okResponse = controller.Create(1, new CommentDataModel { Id = 1, Content = "Content" }); var okResult = okResponse as OkNegotiatedContentResult<CommentDataModel>; Assert.IsNotNull(okResponse); Assert.AreEqual(1, okResult.Content.Id); Assert.AreEqual("Content", okResult.Content.Content); }
private Mock <DbSet <Payment> > GetPayments(bool dataAllowed = true) { IQueryable <Payment> data; if (dataAllowed) { data = new List <Payment>() { new Payment { Id = 1, Booking_id = 1, Customer_id = 1, PaymentMethod_id = 2, Amount = Convert.ToDecimal(6.7800), Deleted = false } }.AsQueryable(); } else { data = Enumerable.Empty <Payment>().AsQueryable(); } Mock <DbSet <Payment> > dataSet = new Mock <DbSet <Payment> >(); dataSet.As <IDbAsyncEnumerable <Payment> >().Setup(m => m.GetAsyncEnumerator()).Returns(new TestDbAsyncEnumerator <Payment>(data.GetEnumerator())); dataSet.As <IQueryable <Payment> >().Setup(m => m.Provider).Returns(new TestDbAsyncQueryProvider <Payment>(data.Provider)); dataSet.As <IQueryable>().Setup(m => m.Provider).Returns(new TestDbAsyncQueryProvider <Payment>(data.Provider)); dataSet.As <IQueryable <Payment> >().Setup(m => m.Expression).Returns(data.Expression); dataSet.As <IQueryable <Payment> >().Setup(m => m.ElementType).Returns(data.ElementType); dataSet.As <IQueryable <Payment> >().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator()); dataSet.Setup(m => m.Add(It.IsAny <Payment>())).Returns((Payment r) => r); return(dataSet); }
private Mock <DbSet <MenuItemType> > GetMenuItemTypes(bool dataAllowed = true) { IQueryable <MenuItemType> data; if (dataAllowed) { data = new List <MenuItemType>() { new MenuItemType { Id = 1, MenuItem_id = 1, Type_id = 1, Deleted = false }, new MenuItemType { Id = 2, MenuItem_id = 2, Type_id = 2, Deleted = false }, new MenuItemType { Id = 3, MenuItem_id = 3, Type_id = 3, Deleted = false } }.AsQueryable(); } else { data = Enumerable.Empty <MenuItemType>().AsQueryable(); } Mock <DbSet <MenuItemType> > dataSet = new Mock <DbSet <MenuItemType> >(); dataSet.As <IDbAsyncEnumerable <MenuItemType> >().Setup(m => m.GetAsyncEnumerator()).Returns(new TestDbAsyncEnumerator <MenuItemType>(data.GetEnumerator())); dataSet.As <IQueryable <MenuItemType> >().Setup(m => m.Provider).Returns(new TestDbAsyncQueryProvider <MenuItemType>(data.Provider)); dataSet.As <IQueryable>().Setup(m => m.Provider).Returns(new TestDbAsyncQueryProvider <MenuItemType>(data.Provider)); dataSet.As <IQueryable <MenuItemType> >().Setup(m => m.Expression).Returns(data.Expression); dataSet.As <IQueryable <MenuItemType> >().Setup(m => m.ElementType).Returns(data.ElementType); dataSet.As <IQueryable <MenuItemType> >().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator()); dataSet.Setup(m => m.Add(It.IsAny <MenuItemType>())).Returns((MenuItemType r) => r); return(dataSet); }
private Mock <DbSet <DietInfo> > GetDietInfo(bool dataAllowed = true) { IQueryable <DietInfo> data; if (dataAllowed) { data = new List <DietInfo>() { new DietInfo { Id = 1, Name = "Vegetarian", Deleted = false }, new DietInfo { Id = 2, Name = "Vegan", Deleted = false }, new DietInfo { Id = 3, Name = "Contains Nuts", Deleted = false } }.AsQueryable(); } else { data = Enumerable.Empty <DietInfo>().AsQueryable(); } Mock <DbSet <DietInfo> > dataSet = new Mock <DbSet <DietInfo> >(); dataSet.As <IDbAsyncEnumerable <DietInfo> >().Setup(m => m.GetAsyncEnumerator()).Returns(new TestDbAsyncEnumerator <DietInfo>(data.GetEnumerator())); dataSet.As <IQueryable <DietInfo> >().Setup(m => m.Provider).Returns(new TestDbAsyncQueryProvider <DietInfo>(data.Provider)); dataSet.As <IQueryable>().Setup(m => m.Provider).Returns(new TestDbAsyncQueryProvider <DietInfo>(data.Provider)); dataSet.As <IQueryable <DietInfo> >().Setup(m => m.Expression).Returns(data.Expression); dataSet.As <IQueryable <DietInfo> >().Setup(m => m.ElementType).Returns(data.ElementType); dataSet.As <IQueryable <DietInfo> >().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator()); dataSet.Setup(m => m.Add(It.IsAny <DietInfo>())).Returns((DietInfo r) => r); return(dataSet); }
private Mock <DbSet <BookingMenuItem> > GetBookingMenuItems(bool dataAllowed = true) { IQueryable <BookingMenuItem> data; if (dataAllowed) { data = new List <BookingMenuItem>() { new BookingMenuItem { Id = 1, Booking_id = 1, MenuItem_id = 2, Quantity = 1, Total = Convert.ToDecimal(6.7800), Deleted = false } }.AsQueryable(); } else { data = Enumerable.Empty <BookingMenuItem>().AsQueryable(); } Mock <DbSet <BookingMenuItem> > dataSet = new Mock <DbSet <BookingMenuItem> >(); dataSet.As <IDbAsyncEnumerable <BookingMenuItem> >().Setup(m => m.GetAsyncEnumerator()).Returns(new TestDbAsyncEnumerator <BookingMenuItem>(data.GetEnumerator())); dataSet.As <IQueryable <BookingMenuItem> >().Setup(m => m.Provider).Returns(new TestDbAsyncQueryProvider <BookingMenuItem>(data.Provider)); dataSet.As <IQueryable>().Setup(m => m.Provider).Returns(new TestDbAsyncQueryProvider <BookingMenuItem>(data.Provider)); dataSet.As <IQueryable <BookingMenuItem> >().Setup(m => m.Expression).Returns(data.Expression); dataSet.As <IQueryable <BookingMenuItem> >().Setup(m => m.ElementType).Returns(data.ElementType); dataSet.As <IQueryable <BookingMenuItem> >().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator()); dataSet.Setup(m => m.Add(It.IsAny <BookingMenuItem>())).Returns((BookingMenuItem r) => r); return(dataSet); }
private Mock <DbSet <DatabaseContext.Data.Type> > GetTypes(bool dataAllowed = true) { IQueryable <DatabaseContext.Data.Type> data; if (dataAllowed) { data = new List <DatabaseContext.Data.Type>() { new DatabaseContext.Data.Type { Id = 1, Name = "Starter", Deleted = false }, new DatabaseContext.Data.Type { Id = 2, Name = "Main", Deleted = false }, new DatabaseContext.Data.Type { Id = 3, Name = "Dessert", Deleted = false } }.AsQueryable(); } else { data = Enumerable.Empty <DatabaseContext.Data.Type>().AsQueryable(); } Mock <DbSet <DatabaseContext.Data.Type> > dataSet = new Mock <DbSet <DatabaseContext.Data.Type> >(); dataSet.As <IDbAsyncEnumerable <DatabaseContext.Data.Type> >().Setup(m => m.GetAsyncEnumerator()).Returns(new TestDbAsyncEnumerator <DatabaseContext.Data.Type>(data.GetEnumerator())); dataSet.As <IQueryable <DatabaseContext.Data.Type> >().Setup(m => m.Provider).Returns(new TestDbAsyncQueryProvider <DatabaseContext.Data.Type>(data.Provider)); dataSet.As <IQueryable>().Setup(m => m.Provider).Returns(new TestDbAsyncQueryProvider <DatabaseContext.Data.Type>(data.Provider)); dataSet.As <IQueryable <DatabaseContext.Data.Type> >().Setup(m => m.Expression).Returns(data.Expression); dataSet.As <IQueryable <DatabaseContext.Data.Type> >().Setup(m => m.ElementType).Returns(data.ElementType); dataSet.As <IQueryable <DatabaseContext.Data.Type> >().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator()); dataSet.Setup(m => m.Add(It.IsAny <DatabaseContext.Data.Type>())).Returns((DatabaseContext.Data.Type r) => r); return(dataSet); }
public static IVsHierarchy Create() { var mock = new Mock <IVsProject4>(); return(mock.As <IVsHierarchy>().Object); }
public void GetAllProjectTest() { var pdata = new List <Project>() { new Project { Project_ID = 1, ProjectName = "TestProject1", StartDate = DateTime.Now, EndDate = DateTime.Now.AddDays(1), Priority = 10, ManagerID = 1, IsSuspended = true, noofTasks = 1, noofCompletedTasks = 1, managerDetails = "Manager1" }, new Project { Project_ID = 2, ProjectName = "TestProject2", StartDate = DateTime.Now, EndDate = DateTime.Now.AddDays(1), Priority = 11, ManagerID = 2, IsSuspended = false, noofTasks = 1, noofCompletedTasks = 1, managerDetails = "Manager1" } }.AsQueryable(); var mock = new Mock <DbSet <Project> >(); mock.As <IQueryable <Project> >().Setup(x => x.Provider).Returns(pdata.Provider); mock.As <IQueryable <Project> >().Setup(x => x.Expression).Returns(pdata.Expression); mock.As <IQueryable <Project> >().Setup(x => x.ElementType).Returns(pdata.ElementType); mock.As <IQueryable <Project> >().Setup(x => x.GetEnumerator()).Returns(pdata.GetEnumerator()); var udata = new List <User>() { new User { User_ID = 1, Employee_ID = "1", FirstName = "FirstName1", LastName = "LastName1" }, new User { User_ID = 2, Employee_ID = "2", FirstName = "FirstName2", LastName = "LastName2" } }.AsQueryable(); var umock = new Mock <DbSet <User> >(); umock.As <IQueryable <User> >().Setup(x => x.Provider).Returns(udata.Provider); umock.As <IQueryable <User> >().Setup(x => x.Expression).Returns(udata.Expression); umock.As <IQueryable <User> >().Setup(x => x.ElementType).Returns(udata.ElementType); umock.As <IQueryable <User> >().Setup(x => x.GetEnumerator()).Returns(udata.GetEnumerator()); var tdata = new List <Task>() { new Task { Task_ID = 1, Parent_ID = 1, Project_ID = 1, TaskName = "TestTask1", StartDate = DateTime.Now, EndDate = DateTime.Now.AddDays(1), Priority = 10, User_ID = 1, IsParentTask = true, ParentTaskName = "ParentTask1", UserName = "******", ProjectName = "TestProject1" }, new Task { Task_ID = 2, Parent_ID = 1, Project_ID = 1, TaskName = "TestTask2", StartDate = DateTime.Now, EndDate = DateTime.Now.AddDays(1), Priority = 10, User_ID = 1, IsParentTask = true, ParentTaskName = "ParentTask1", UserName = "******", ProjectName = "TestProject1" } }.AsQueryable(); var tmock = new Mock <DbSet <Task> >(); tmock.As <IQueryable <Task> >().Setup(x => x.Provider).Returns(tdata.Provider); tmock.As <IQueryable <Task> >().Setup(x => x.Expression).Returns(tdata.Expression); tmock.As <IQueryable <Task> >().Setup(x => x.ElementType).Returns(tdata.ElementType); tmock.As <IQueryable <Task> >().Setup(x => x.GetEnumerator()).Returns(tdata.GetEnumerator()); var context = new Mock <ProjectManagerContext>(); context.Setup(x => x.projects).Returns(mock.Object); context.Setup(x => x.users).Returns(umock.Object); context.Setup(x => x.tasks).Returns(tmock.Object); var service = new ProjectRepository(context.Object); List <Project> users = service.GetAllProjects(); Assert.That(users.Count == 2); }
public static DTE2 Create() { var mock = new Mock <DTE>(); return(mock.As <DTE2>().Object); }
public static void ClassInitialize(TestContext context) { mockContext = new Mock <RegionCityContext>(); mockRegionSet = new Mock <DbSet <Region> >(); mockCitySet = new Mock <DbSet <City> >(); // Arrange data providers citiesProvider = new List <City>() { new City { CityName = "Berlin", Region = new Region { RegionName = "Berlin" } }, new City { CityName = "Hamburg", Region = new Region { RegionName = "Hamburg" } }, new City { CityName = "Munich", Region = new Region { RegionName = "Bavaria" } }, new City { CityName = "Cologne", Region = new Region { RegionName = "North Rhine-Westphalia" } }, new City { CityName = "Frankfurt am Main", Region = new Region { RegionName = "Hesse" } } }; regionsProvider = new List <Region>() { new Region { RegionName = "Berlin" }, new Region { RegionName = "Hamburg" }, new Region { RegionName = "Bavaria" }, new Region { RegionName = "North Rhine-Westphalia" }, new Region { RegionName = "Hesse" } }; // mockCitySet setup mockCitySet.As <IQueryable <City> >().Setup(m => m.Provider).Returns(citiesProvider.AsQueryable().Provider); mockCitySet.As <IQueryable <City> >().Setup(m => m.Expression).Returns(citiesProvider.AsQueryable().Expression); mockCitySet.As <IQueryable <City> >().Setup(m => m.ElementType).Returns(citiesProvider.AsQueryable().ElementType); mockCitySet.As <IQueryable <City> >().Setup(m => m.GetEnumerator()).Returns(citiesProvider.AsQueryable().GetEnumerator()); // mockRegionSet setup mockRegionSet.As <IQueryable <Region> >().Setup(m => m.Provider).Returns(regionsProvider.AsQueryable().Provider); mockRegionSet.As <IQueryable <Region> >().Setup(m => m.Expression).Returns(regionsProvider.AsQueryable().Expression); mockRegionSet.As <IQueryable <Region> >().Setup(m => m.ElementType).Returns(regionsProvider.AsQueryable().ElementType); mockRegionSet.As <IQueryable <Region> >().Setup(m => m.GetEnumerator()).Returns(regionsProvider.AsQueryable().GetEnumerator()); // mockContext setup mockContext.Setup(c => c.Regions).Returns(mockRegionSet.Object); mockContext.Setup(c => c.Set <Region>()).Returns(mockRegionSet.Object); mockContext.Setup(c => c.Cities).Returns(mockCitySet.Object); mockContext.Setup(c => c.Set <City>()).Returns(mockCitySet.Object); }
public async Task TestPostAudioJob() { //init var mockJobs = new Mock <DbSet <Job> >(); var mockServiceUsers = new Mock <DbSet <ServiceUser> >(); var mockContext = new Mock <RoboBrailleDataContext>(); var mockAuSender = new Mock <IAudioJobSender>(); // arrange var users = new List <ServiceUser> { new ServiceUser { EmailAddress = "*****@*****.**", UserId = Guid.Parse("d2b97532-e8c5-e411-8270-f0def103cfd0"), ApiKey = Encoding.UTF8.GetBytes("7b76ae41-def3-e411-8030-0c8bfd2336cd"), FromDate = new DateTime(2015, 1, 1), ToDate = new DateTime(2020, 1, 1), UserName = "******", Jobs = null } }.AsQueryable(); AudioJob auj = new AudioJob() { Id = Guid.NewGuid(), FileContent = new byte[512], UserId = Guid.Parse("d2b97532-e8c5-e411-8270-f0def103cfd0"), FileExtension = ".pdf", FileName = "test", MimeType = "application/pdf", Status = JobStatus.Started, SubmitTime = DateTime.Now, DownloadCounter = 0, InputFileHash = new byte[64], AudioLanguage = Language.daDK, FormatOptions = AudioFormat.Mp3, SpeedOptions = AudioSpeed.Normal, VoicePropriety = new VoicePropriety[] { VoicePropriety.Anne } }; AudioJob auj2 = new AudioJob() { Id = Guid.NewGuid(), FileContent = new byte[256], UserId = Guid.Parse("d2b87532-e8c5-e411-8270-f0def103cfd0"), FileExtension = ".txt", FileName = "test2", MimeType = "text/plain", Status = JobStatus.Done, SubmitTime = DateTime.Now, DownloadCounter = 2, InputFileHash = new byte[2] }; var jobs = new List <AudioJob> { auj2 }.AsQueryable(); mockJobs.As <IDbAsyncEnumerable <Job> >().Setup(m => m.GetAsyncEnumerator()).Returns(new TestDbAsyncEnumerator <Job>(jobs.GetEnumerator())); mockJobs.As <IQueryable <Job> >().Setup(m => m.Provider).Returns(new TestDbAsyncQueryProvider <Job>(jobs.Provider)); mockJobs.As <IQueryable <Job> >().Setup(m => m.Expression).Returns(jobs.Expression); mockJobs.As <IQueryable <Job> >().Setup(m => m.ElementType).Returns(jobs.ElementType); mockJobs.As <IQueryable <Job> >().Setup(m => m.GetEnumerator()).Returns(jobs.GetEnumerator()); mockServiceUsers.As <IDbAsyncEnumerable <ServiceUser> >().Setup(m => m.GetAsyncEnumerator()).Returns(new TestDbAsyncEnumerator <ServiceUser>(users.GetEnumerator())); mockServiceUsers.As <IQueryable <ServiceUser> >().Setup(m => m.Provider).Returns(new TestDbAsyncQueryProvider <ServiceUser>(users.Provider)); mockServiceUsers.As <IQueryable <ServiceUser> >().Setup(m => m.Expression).Returns(users.Expression); mockServiceUsers.As <IQueryable <ServiceUser> >().Setup(m => m.ElementType).Returns(users.ElementType); mockServiceUsers.As <IQueryable <ServiceUser> >().Setup(m => m.GetEnumerator()).Returns(users.GetEnumerator()); mockContext.Setup(m => m.Jobs).Returns(mockJobs.Object); mockContext.Setup(m => m.ServiceUsers).Returns(mockServiceUsers.Object); mockAuSender.Setup(m => m.SendAudioJobToQueue(auj)).Returns(Encoding.UTF8.GetBytes(testFileResult)); var repo = new AudioRepository(mockContext.Object, mockAuSender.Object); var request = new HttpRequestMessage(); request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Authorization", "Hawk id=\"d2b97532-e8c5-e411-8270-f0def103cfd0\", ts=\"1470657024\", nonce=\"VkcMGB\", mac=\"hXW+BLRoqwlUaQZQtpPToOWnVAh5KbAXGGT5f8dLMVk=\""); var serviceController = new AudioController(repo) { Request = request }; //call await serviceController.Post(auj); //test mockJobs.Verify(m => m.Add(It.IsAny <Job>()), Times.Once()); mockContext.Verify(m => m.SaveChanges(), Times.Exactly(1)); //twice if it is synced //mockContext.Verify(m => m.SaveChanges(), Times.Exactly(2)); mockAuSender.Verify(m => m.SendAudioJobToQueue(It.IsAny <AudioJob>()), Times.Once()); Assert.IsFalse(File.Exists(testFileResult)); }
public override TDbContext Create() { var dbContextMock = new Mock <TDbContext>(ConstructorParameters.ToArray()); dbContextMock.DefaultValueProvider = new NoSetUpDefaultValueProvider <TDbContext>(DbContext); dbContextMock.Setup(m => m.Add(It.IsAny <object>())).Returns((object providedEntity) => DbContext.Add(providedEntity)); dbContextMock.Setup(m => m.AddAsync(It.IsAny <object>(), It.IsAny <CancellationToken>())) .Returns((object providedEntity, CancellationToken providedCancellationToken) => DbContext.AddAsync(providedEntity, providedCancellationToken)); dbContextMock.Setup(m => m.AddRange(It.IsAny <object[]>())).Callback((object[] providedEntities) => DbContext.AddRange(providedEntities)); dbContextMock.Setup(m => m.AddRange(It.IsAny <IEnumerable <object> >())).Callback((IEnumerable <object> providedEntities) => DbContext.AddRange(providedEntities)); dbContextMock.Setup(m => m.AddRangeAsync(It.IsAny <object[]>(), It.IsAny <CancellationToken>())) .Returns((object[] providedEntities, CancellationToken providedCancellationToken) => DbContext.AddRangeAsync(providedEntities, providedCancellationToken)); dbContextMock.Setup(m => m.AddRangeAsync(It.IsAny <IEnumerable <object> >(), It.IsAny <CancellationToken>())) .Returns((IEnumerable <object> providedEntities, CancellationToken providedCancellationToken) => DbContext.AddRangeAsync(providedEntities, providedCancellationToken)); dbContextMock.Setup(m => m.Attach(It.IsAny <object>())).Returns((object providedEntity) => DbContext.Attach(providedEntity)); dbContextMock.Setup(m => m.AttachRange(It.IsAny <object[]>())).Callback((object[] providedEntities) => DbContext.AttachRange(providedEntities)); dbContextMock.Setup(m => m.AttachRange(It.IsAny <IEnumerable <object> >())).Callback((IEnumerable <object> providedEntities) => DbContext.AttachRange(providedEntities)); dbContextMock.As <IDbContextDependencies>().Setup(m => m.ChangeDetector).Returns(((IDbContextDependencies)DbContext).ChangeDetector); dbContextMock.Setup(m => m.ChangeTracker).Returns(() => DbContext.ChangeTracker); dbContextMock.Setup(m => m.ContextId).Returns(() => DbContext.ContextId); dbContextMock.Setup(m => m.Database).Returns(() => DbContext.Database); dbContextMock.Setup(m => m.Dispose()).Callback(() => DbContext.Dispose()); dbContextMock.Setup(m => m.DisposeAsync()).Callback(() => DbContext.DisposeAsync()); dbContextMock.As <IDbContextDependencies>().Setup(m => m.EntityFinderFactory).Returns(((IDbContextDependencies)DbContext).EntityFinderFactory); dbContextMock.As <IDbContextDependencies>().Setup(m => m.EntityGraphAttacher).Returns(((IDbContextDependencies)DbContext).EntityGraphAttacher); dbContextMock.Setup(m => m.Entry(It.IsAny <object>())).Returns((object providedEntity) => DbContext.Entry(providedEntity)); dbContextMock.Setup(m => m.Find(It.IsAny <Type>(), It.IsAny <object[]>())) .Returns((Type providedEntityType, object[] providedKeyValues) => DbContext.Find(providedEntityType, providedKeyValues)); dbContextMock.Setup(m => m.FindAsync(It.IsAny <Type>(), It.IsAny <object[]>())) .Returns((Type providedEntityType, object[] providedKeyValues) => DbContext.FindAsync(providedEntityType, providedKeyValues)); dbContextMock.Setup(m => m.FindAsync(It.IsAny <Type>(), It.IsAny <object[]>(), It.IsAny <CancellationToken>())) .Returns((Type providedEntityType, object[] providedKeyValues, CancellationToken providedCancellationToken) => DbContext.FindAsync(providedEntityType, providedKeyValues, providedCancellationToken)); dbContextMock.As <IDbSetCache>() .Setup(m => m.GetOrAddSet(It.IsAny <IDbSetSource>(), It.IsAny <Type>())) .Returns((IDbSetSource providedSource, Type providedType) => ((IDbSetCache)DbContext).GetOrAddSet(providedSource, providedType)); dbContextMock.As <IDbContextDependencies>().Setup(m => m.InfrastructureLogger).Returns(((IDbContextDependencies)DbContext).InfrastructureLogger); dbContextMock.As <IInfrastructure <IServiceProvider> >().Setup(m => m.Instance).Returns(((IInfrastructure <IServiceProvider>)DbContext).Instance); //dbContextMock.As<IDbContextDependencies>().Setup(m => m.Model).Returns(((IDbContextDependencies) DbContext).Model); dbContextMock.As <IDbContextDependencies>().Setup(m => m.QueryProvider).Returns(((IDbContextDependencies)DbContext).QueryProvider); dbContextMock.Setup(m => m.Remove(It.IsAny <object>())).Returns((object providedEntity) => DbContext.Remove(providedEntity)); dbContextMock.Setup(m => m.RemoveRange(It.IsAny <IEnumerable <object> >())).Callback((IEnumerable <object> providedEntities) => DbContext.RemoveRange(providedEntities)); dbContextMock.Setup(m => m.RemoveRange(It.IsAny <object[]>())).Callback((object[] providedEntities) => DbContext.RemoveRange(providedEntities)); dbContextMock.As <IDbContextPoolable>().Setup(m => m.ResetState()).Callback(((IDbContextPoolable)DbContext).ResetState); dbContextMock.As <IDbContextPoolable>() .Setup(m => m.ResetStateAsync(It.IsAny <CancellationToken>())) .Callback((CancellationToken providedCancellationToken) => ((IDbContextPoolable)DbContext).ResetStateAsync(providedCancellationToken)); // dbContextMock.As<IDbContextPoolable>() // .Setup(m => m.Resurrect(It.IsAny<DbContextPoolConfigurationSnapshot>())) // .Callback((DbContextPoolConfigurationSnapshot providedConfigurationSnapshot) => ((IDbContextPoolable) DbContext).Resurrect(providedConfigurationSnapshot)); dbContextMock.Setup(m => m.SaveChanges()).Returns(() => DbContext.SaveChanges()); dbContextMock.Setup(m => m.SaveChanges(It.IsAny <bool>())).Returns((bool providedAcceptAllChangesOnSuccess) => DbContext.SaveChanges(providedAcceptAllChangesOnSuccess)); dbContextMock.Setup(m => m.SaveChangesAsync(It.IsAny <CancellationToken>())) .Returns((CancellationToken providedCancellationToken) => DbContext.SaveChangesAsync(providedCancellationToken)); dbContextMock.Setup(m => m.SaveChangesAsync(It.IsAny <bool>(), It.IsAny <CancellationToken>())) .Returns((bool providedAcceptAllChangesOnSuccess, CancellationToken providedCancellationToken) => DbContext.SaveChangesAsync(providedAcceptAllChangesOnSuccess, providedCancellationToken)); // dbContextMock.As<IDbContextPoolable>() // .Setup(m => m.SetPool(It.IsAny<IDbContextPool>())) // .Callback((IDbContextPool providedContextPool) => ((IDbContextPoolable) DbContext).SetPool(providedContextPool)); dbContextMock.As <IDbContextDependencies>().Setup(m => m.SetSource).Returns(((IDbContextDependencies)DbContext).SetSource); // dbContextMock.As<IDbContextPoolable>().Setup(m => m.SnapshotConfiguration()).Returns(((IDbContextPoolable) DbContext).SnapshotConfiguration()); dbContextMock.As <IDbContextDependencies>().Setup(m => m.StateManager).Returns(((IDbContextDependencies)DbContext).StateManager); dbContextMock.Setup(m => m.Update(It.IsAny <object>())).Returns((object providedEntity) => DbContext.Update(providedEntity)); dbContextMock.As <IDbContextDependencies>().Setup(m => m.UpdateLogger).Returns(((IDbContextDependencies)DbContext).UpdateLogger); dbContextMock.Setup(m => m.UpdateRange(It.IsAny <IEnumerable <object> >())).Callback((IEnumerable <object> providedEntities) => DbContext.UpdateRange(providedEntities)); dbContextMock.Setup(m => m.UpdateRange(It.IsAny <object[]>())).Callback((object[] providedEntities) => DbContext.UpdateRange(providedEntities)); //Relational set up var rawSqlCommandBuilderMock = new Mock <IRawSqlCommandBuilder>(); rawSqlCommandBuilderMock.Setup(m => m.Build(It.IsAny <string>(), It.IsAny <IEnumerable <object> >())) .Callback((string providedSql, IEnumerable <object> providedParameters) => Logger.LogDebug("Catch all exception invoked")) .Throws <InvalidOperationException>(); var rawSqlCommandBuilder = rawSqlCommandBuilderMock.Object; // var concurrencyDetectorMock = new Mock<IConcurrencyDetector>(); // concurrencyDetectorMock.Setup(x => x.EnterCriticalSection()).Returns(() => new ConcurrencyDetectorCriticalSectionDisposer(Mock.Of<IConcurrencyDetector>())); // var concurrencyDetector = concurrencyDetectorMock.Object; var relationalConnectionMock = new Mock <IRelationalConnection>(); relationalConnectionMock.Setup(x => x.CommandTimeout).Returns(() => 0); var relationalConnection = relationalConnectionMock.Object; var dependenciesMock = new Mock <IRelationalDatabaseFacadeDependencies>(); //dependenciesMock.Setup(m => m.ConcurrencyDetector).Returns(() => concurrencyDetector); dependenciesMock.Setup(m => m.CommandLogger).Returns(() => Mock.Of <IRelationalCommandDiagnosticsLogger>()); dependenciesMock.Setup(m => m.RawSqlCommandBuilder).Returns(() => rawSqlCommandBuilder); dependenciesMock.Setup(m => m.RelationalConnection).Returns(() => relationalConnection); //dependenciesMock.Setup(m => m.CoreOptions.IsConcurrencyDetectionEnabled).Returns(() => true); dependenciesMock.Setup(m => m.CoreOptions.AreThreadSafetyChecksEnabled).Returns(() => false); var dependencies = dependenciesMock.Object; var serviceProviderMock = new Mock <IServiceProvider>(); serviceProviderMock.Setup(m => m.GetService(It.Is <Type>(t => t == typeof(IDatabaseFacadeDependencies)))).Returns((Type providedType) => dependencies); var serviceProvider = serviceProviderMock.Object; dbContextMock.As <IInfrastructure <IServiceProvider> >().Setup(m => m.Instance).Returns(() => serviceProvider); var mockedDbContext = dbContextMock.Object; var databaseFacadeMock = new Mock <DatabaseFacade>(mockedDbContext); databaseFacadeMock.As <IDatabaseFacadeDependenciesAccessor>().Setup(x => x.Dependencies).Returns(() => dependencies); databaseFacadeMock.Setup(x => x.BeginTransaction()).Returns(() => Mock.Of <IDbContextTransaction>()); var databaseFacade = databaseFacadeMock.Object; dbContextMock.Setup(m => m.Database).Returns(() => databaseFacade); return(mockedDbContext); }
private static PatientsController GetPatientsControllerForGetPatientsMethod( IEnumerable <User> dbUsers = null, IEnumerable <Doctor> dbDoctors = null, IEnumerable <Patient> dbPatients = null, IEnumerable <Appointment> dbAppointments = null, string identityRole = "" ) { var mockContext = new Mock <AlphaMedicContext>(); if (dbUsers != null) { var mockSet = new Mock <DbSet <User> >(); mockSet.As <IQueryable <User> >().Setup(m => m.Provider).Returns(dbUsers.AsQueryable().Provider); mockSet.As <IQueryable <User> >().Setup(m => m.Expression).Returns(dbUsers.AsQueryable().Expression); mockSet.As <IQueryable <User> >().Setup(m => m.ElementType).Returns(dbUsers.AsQueryable().ElementType); mockSet.As <IQueryable <User> >().Setup(m => m.GetEnumerator()).Returns(() => dbUsers.AsQueryable().GetEnumerator()); mockContext.Setup(c => c.Users).Returns(mockSet.Object); } if (dbPatients != null) { var mockSet = new Mock <DbSet <Patient> >(); mockSet.As <IQueryable <Patient> >().Setup(m => m.Provider).Returns(dbPatients.AsQueryable().Provider); mockSet.As <IQueryable <Patient> >().Setup(m => m.Expression).Returns(dbPatients.AsQueryable().Expression); mockSet.As <IQueryable <Patient> >().Setup(m => m.ElementType).Returns(dbPatients.AsQueryable().ElementType); mockSet.As <IQueryable <Patient> >().Setup(m => m.GetEnumerator()).Returns(() => dbPatients.AsQueryable().GetEnumerator()); mockSet.Setup(m => m.Include("Appointments")).Returns(mockSet.Object); mockContext.Setup(c => c.Patients).Returns(mockSet.Object); } if (dbDoctors != null) { var mockSet = new Mock <DbSet <Doctor> >(); mockSet.As <IQueryable <Doctor> >().Setup(m => m.Provider).Returns(dbDoctors.AsQueryable().Provider); mockSet.As <IQueryable <Doctor> >().Setup(m => m.Expression).Returns(dbDoctors.AsQueryable().Expression); mockSet.As <IQueryable <Doctor> >().Setup(m => m.ElementType).Returns(dbDoctors.AsQueryable().ElementType); mockSet.As <IQueryable <Doctor> >().Setup(m => m.GetEnumerator()).Returns(() => dbDoctors.AsQueryable().GetEnumerator()); mockContext.Setup(c => c.Doctors).Returns(mockSet.Object); } if (dbAppointments != null) { var mockSet = new Mock <DbSet <Appointment> >(); mockSet.As <IQueryable <Appointment> >().Setup(m => m.Provider).Returns(dbAppointments.AsQueryable().Provider); mockSet.As <IQueryable <Appointment> >().Setup(m => m.Expression).Returns(dbAppointments.AsQueryable().Expression); mockSet.As <IQueryable <Appointment> >().Setup(m => m.ElementType).Returns(dbAppointments.AsQueryable().ElementType); mockSet.As <IQueryable <Appointment> >().Setup(m => m.GetEnumerator()).Returns(() => dbAppointments.AsQueryable().GetEnumerator()); //mockContext.Setup(m => m.Include("Appointments")).Returns(mockPersonSet.Object); } var service = new PatientsController(mockContext.Object); service.User = new GenericPrincipal( new GenericIdentity( "*****@*****.**", "Passport"), new[] { identityRole }); return(service); }
public void BeforeEach() { _webElementMock = new Mock <IWebElement>(); _javaScriptExecutorMock = _webElementMock.As <IJavaScriptExecutor>(); }
public static XafApplication NewApplication <TModule>(this Platform platform, bool transmitMessage = true, bool handleExceptions = true, bool usePersistentStorage = false) where TModule : ModuleBase { XafApplication application; ApplicationModulesManager.UseStaticCache = false; string applicationTypeName; if (platform == Platform.Web) { applicationTypeName = "Xpand.TestsLib.TestWebApplication"; application = (XafApplication)AppDomain.CurrentDomain.CreateTypeInstance(applicationTypeName, typeof(TModule), transmitMessage); } else if (platform == Platform.Win) { applicationTypeName = "Xpand.TestsLib.TestWinApplication"; application = (XafApplication)AppDomain.CurrentDomain.CreateTypeInstance(applicationTypeName, typeof(TModule), transmitMessage, handleExceptions); } else if (platform == Platform.Blazor) { application = (XafApplication)ApplicationType.CreateInstance(typeof(TModule), transmitMessage, handleExceptions); } else { throw new NotSupportedException( "if implemented make sure all tests pass with TestExplorer and live testing"); } application.Title = TestContext.CurrentContext.Test.FullName; application.ConnectionString = usePersistentStorage? @$ "Integrated Security=SSPI;Pooling=false;Data Source=(localdb)\mssqllocaldb;Initial Catalog={typeof(TModule).Name}":InMemoryDataStoreProvider.ConnectionString; application.DatabaseUpdateMode = DatabaseUpdateMode.UpdateDatabaseAlways; application.CheckCompatibilityType = CheckCompatibilityType.DatabaseSchema; application.ConfigureModel <TModule>(transmitMessage).SubscribeReplay(); application.MockEditorsFactory(); if (platform == Platform.Web) { var frameTemplateFactoryMock = new Mock <IFrameTemplateFactory>(); var frameTemplateMock = new Mock <IFrameTemplate>() { CallBase = true }; frameTemplateMock.Setup(template => template.GetContainers()).Returns(new ActionContainerCollection()); frameTemplateFactoryMock.Setup(factory => factory.CreateTemplate(It.IsAny <TemplateContext>())).Returns( (TemplateContext context) => { if (context == TemplateContext.NestedFrame) { return((IFrameTemplate)frameTemplateMock.As <ISupportActionsToolbarVisibility>().Object); } return(frameTemplateMock.Object); }); application.SetPropertyValue("FrameTemplateFactory", frameTemplateFactoryMock.Object); } else if (platform == Platform.Win) { application.SetPropertyValue("UseLightStyle", true); } return(application); }
public void MockTemplateContext() { //initialize Answer answer = new Answer { Id = 1, AnswerText = "Отговор 1", Correct = 1, WrongText = "" }; Answer answer2 = new Answer { Id = 2, AnswerText = "Отговор 2", Correct = 0, WrongText = "" }; Answer answer3 = new Answer { Id = 3, AnswerText = "Отговор 3", Correct = 0, WrongText = "" }; List <Answer> answers = new List <Answer> { answer, answer2, answer3 }; var data1 = new List <Answer> { answer, answer2, answer3 }.AsQueryable(); var mockAnswer = new Mock <DbSet <Answer> >(); mockAnswer.As <IQueryable <Answer> >().Setup(m => m.Provider).Returns(data1.Provider); mockAnswer.As <IQueryable <Answer> >().Setup(m => m.Expression).Returns(data1.Expression); mockAnswer.As <IQueryable <Answer> >().Setup(m => m.ElementType).Returns(data1.ElementType); mockAnswer.As <IQueryable <Answer> >().Setup(m => m.GetEnumerator()).Returns(data1.GetEnumerator()); Question question = new Question { Answers = answers, Id = 1, QuestionText = "Въпрос", Score = 2, WrongText = "" }; List <Question> questions = new List <Question> { question }; var data2 = new List <Question> { question }.AsQueryable(); var mockQuestion = new Mock <DbSet <Question> >(); mockQuestion.As <IQueryable <Question> >().Setup(m => m.Provider).Returns(data2.Provider); mockQuestion.As <IQueryable <Question> >().Setup(m => m.Expression).Returns(data2.Expression); mockQuestion.As <IQueryable <Question> >().Setup(m => m.ElementType).Returns(data2.ElementType); mockQuestion.As <IQueryable <Question> >().Setup(m => m.GetEnumerator()).Returns(data2.GetEnumerator()); var questionResponse = new QuestionResponse { Id = 1, Question = question, SelectedAnswers = new List <Answer> { answer }, TextAnswer = "" }; List <QuestionResponse> questionResponses = new List <QuestionResponse> { questionResponse }; var data3 = new List <QuestionResponse> { questionResponse }.AsQueryable(); var mockQuestionR = new Mock <DbSet <QuestionResponse> >(); mockQuestionR.As <IQueryable <QuestionResponse> >().Setup(m => m.Provider).Returns(data3.Provider); mockQuestionR.As <IQueryable <QuestionResponse> >().Setup(m => m.Expression).Returns(data3.Expression); mockQuestionR.As <IQueryable <QuestionResponse> >().Setup(m => m.ElementType).Returns(data3.ElementType); mockQuestionR.As <IQueryable <QuestionResponse> >().Setup(m => m.GetEnumerator()).Returns(data3.GetEnumerator()); Score score = new Score { Id = 1, CurrentScore = 2, MaxScore = 2, Note = "" }; var data4 = new List <Score> { score }.AsQueryable(); var mockScore = new Mock <DbSet <Score> >(); mockScore.As <IQueryable <Score> >().Setup(m => m.Provider).Returns(data4.Provider); mockScore.As <IQueryable <Score> >().Setup(m => m.Expression).Returns(data4.Expression); mockScore.As <IQueryable <Score> >().Setup(m => m.ElementType).Returns(data4.ElementType); mockScore.As <IQueryable <Score> >().Setup(m => m.GetEnumerator()).Returns(data4.GetEnumerator()); Test test = new Test { Id = 1, Test_Name = "Начално ниво", Questions = questions }; var data5 = new List <Test> { test }.AsQueryable(); var mockTest = new Mock <DbSet <Test> >(); mockTest.As <IQueryable <Test> >().Setup(m => m.Provider).Returns(data5.Provider); mockTest.As <IQueryable <Test> >().Setup(m => m.Expression).Returns(data5.Expression); mockTest.As <IQueryable <Test> >().Setup(m => m.ElementType).Returns(data5.ElementType); mockTest.As <IQueryable <Test> >().Setup(m => m.GetEnumerator()).Returns(data5.GetEnumerator()); var answerSheet = new AnswerSheet { Id = 1, QuestionResponses = questionResponses, Score = score, Test = test, UserId = "1", UserName = "******" }; var data = new List <AnswerSheet> { answerSheet }.AsQueryable(); var mockSet = new Mock <DbSet <AnswerSheet> >(); mockSet.As <IQueryable <AnswerSheet> >().Setup(m => m.Provider).Returns(data.Provider); mockSet.As <IQueryable <AnswerSheet> >().Setup(m => m.Expression).Returns(data.Expression); mockSet.As <IQueryable <AnswerSheet> >().Setup(m => m.ElementType).Returns(data.ElementType); mockSet.As <IQueryable <AnswerSheet> >().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator()); var user = new AspNetUsers { Id = "1", UserName = "******", NormalizedUserName = "******", Email = "*****@*****.**", NormalizedEmail = "*****@*****.**", EmailConfirmed = false, PasswordHash = "AQAAAAEAACcQAAAAEDRMWdzHFXGRE3SgwHOq8nNPbPlucCQjPRkfK54J9YXxCjg7p2fk6Q1S83UnNINPFw==", SecurityStamp = "M6KU2AJELWWYDCKBRZOJS6TZ4S2O3J3U", ConcurrencyStamp = "93de2d96-9c3f-4c51-8676-4ca10ab68656", PhoneNumber = "NULL", PhoneNumberConfirmed = false, TwoFactorEnabled = false, LockoutEnd = null, LockoutEnabled = true, AccessFailedCount = 0 }; var data6 = new List <AspNetUsers> { user }.AsQueryable(); var mockUser = new Mock <DbSet <AspNetUsers> >(); mockSet.As <IQueryable <AspNetUsers> >().Setup(m => m.Provider).Returns(data6.Provider); mockSet.As <IQueryable <AspNetUsers> >().Setup(m => m.Expression).Returns(data6.Expression); mockSet.As <IQueryable <AspNetUsers> >().Setup(m => m.ElementType).Returns(data6.ElementType); mockSet.As <IQueryable <AspNetUsers> >().Setup(m => m.GetEnumerator()).Returns(data6.GetEnumerator()); var mockContext = new Mock <Brainzzler_DBContext>(); mockContext.Setup(set => set.AnswerSheet).Returns(mockSet.Object); mockContext.Setup(set => set.Answers).Returns(mockAnswer.Object); mockContext.Setup(set => set.Questions).Returns(mockQuestion.Object); mockContext.Setup(set => set.QuestionResponse).Returns(mockQuestionR.Object); mockContext.Setup(set => set.Score).Returns(mockScore.Object); mockContext.Setup(set => set.Tests).Returns(mockTest.Object); mockContext.Setup(set => set.AspNetUsers).Returns(mockUser.Object); }
public void GetFollowingMessages() { //Create a "result set" of messages var messagesData = new List <Message> { new Message { Id = 1, UserName = "******", Text = "Message from user 1", TimeStamp = DateTime.Now }, new Message { Id = 2, UserName = "******", Text = "Message from user 2", TimeStamp = DateTime.Now }, new Message { Id = 3, UserName = "******", Text = "Message from user 2", TimeStamp = DateTime.Now }, new Message { Id = 4, UserName = "******", Text = "Message from user 3", TimeStamp = DateTime.Now } }.AsQueryable(); //Create a "result set" of users var followingUserData = new List <FollowUser> { new FollowUser { Id = 1, User = "******", UserToFollow = "user 2" }, new FollowUser { Id = 2, User = "******", UserToFollow = "user 3" }, new FollowUser { Id = 3, User = "******", UserToFollow = "user 4" }, new FollowUser { Id = 4, User = "******", UserToFollow = "user 1" }, }.AsQueryable(); //Using empty constructor for mocking purpose var usersDbContextMock = new Mock <UsersDbContext>(); //Mock the DbSet to interact with var mockSetOfMessages = new Mock <DbSet <Message> >(); var mockSetOfFollowUser = new Mock <DbSet <FollowUser> >(); //Mock all methods we are using //First follow users mockSetOfFollowUser.As <IQueryable <FollowUser> >().Setup(m => m.Provider).Returns(followingUserData.Provider); mockSetOfFollowUser.As <IQueryable <FollowUser> >().Setup(m => m.Expression).Returns(followingUserData.Expression); //Second messages mockSetOfMessages.As <IQueryable <Message> >().Setup(m => m.Provider).Returns(messagesData.Provider); mockSetOfMessages.As <IQueryable <Message> >().Setup(m => m.Expression).Returns(messagesData.Expression); //Specify when to return it usersDbContextMock.Setup(m => m.Messages).Returns(mockSetOfMessages.Object); usersDbContextMock.Setup(m => m.Users).Returns(mockSetOfFollowUser.Object); //Using empty constructor for mocking purpose var applicationDbContextMock = new Mock <ApplicationDbContext>(); //Mock the logger var logger = new Mock <ILogger <Messages> >(); Messages messages = new Messages( usersDbContextMock.Object, logger.Object); //Assert that it was successful Assert.True(messages.GetFollowingMessages("user 1").Count() == 2); //Verify that we have saved the change usersDbContextMock.Verify(m => m.Messages, Times.Once()); usersDbContextMock.Verify(m => m.Users, Times.Once()); }
public ExpedienteBLLTests() { var lista = new List <Expediente> { new Expediente() { ExpedienteId = 1, Cuantia = 525000, Descripcion = "Esto es una descripcion", DireccionEjecutado = "Esto es una direccion", DireccionTituloEjecutivo = "Esto es una direcciond e titulo ejecutivo", EntidadEncargada = "Entidad encargada es maira", FechaRadicacion = new DateTime(2017, 03, 19), Identificacion = "1065824563", NaturalezaObligacion = "Naturaleza es algo", Nombre = "Maira mindiola", UbicacionExpediente = "Esta en el lote tal", }, new Expediente() { ExpedienteId = 2, Cuantia = 525000, Descripcion = "Esto es una descripcion", DireccionEjecutado = "Esto es una direccion", DireccionTituloEjecutivo = "Esto es una direcciond e titulo ejecutivo", EntidadEncargada = "Entidad encargada es maira", FechaRadicacion = new DateTime(2017, 03, 19), Identificacion = "1065824563", NaturalezaObligacion = "Naturaleza es algo", Nombre = "Maira mindiola", UbicacionExpediente = "Esta en el lote tal", }, new Expediente() { ExpedienteId = 3, Cuantia = 555000, Descripcion = "Esto es una descripcion", DireccionEjecutado = "Esto es una direccion", DireccionTituloEjecutivo = "Esto es una direcciond e titulo ejecutivo", EntidadEncargada = "Entidad encargada es maira", FechaRadicacion = new DateTime(2017, 03, 19), Identificacion = "1065824563", NaturalezaObligacion = "Naturaleza es algo", Nombre = "Maira mindiola", UbicacionExpediente = "Esta en el lote tal", } }; var dbContext = new Mock <ApplicationDbContext>(); var data = lista.AsQueryable(); var mockSet = new Mock <DbSet <Expediente> >(); mockSet.As <IQueryable <Expediente> >().Setup(m => m.Provider).Returns(data.Provider); mockSet.As <IQueryable <Expediente> >().Setup(m => m.Expression).Returns(data.Expression); mockSet.As <IQueryable <Expediente> >().Setup(m => m.ElementType).Returns(data.ElementType); mockSet.As <IQueryable <Expediente> >().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator()); var mockContext = new Mock <ApplicationDbContext>(); mockContext.Setup(c => c.Expedientes).Returns(mockSet.Object); servicio = new ExpedienteBLL(mockContext.Object); }
public void CounterStatusCheck() { //Für den ServiceProviderMock //Muss enthalten sein, damit der Mock nicht überschrieben wird IServiceProvider unused = ServiceManager.ServiceProvider; //Feld Infos holen System.Reflection.FieldInfo instance = typeof(ServiceManager).GetField("_serviceProvider", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic); //Mocksaufsetzen //ServiceProvider Mock <IServiceProvider> mockSingleton = new Mock <IServiceProvider>(); Mock <IActivityManager> activityManagerMock = new Mock <IActivityManager>(); Mock <IServiceProvider> activityProviderMock = new Mock <IServiceProvider>(); Mock <AbstractStepActivity> stepActivityMock = new Mock <AbstractStepActivity>(); Mock <AbstractRunningActivity> runningActivityMock = new Mock <AbstractRunningActivity>(); Mock <IEarablesConnection> connectionMock = new Mock <IEarablesConnection>(); Mock <IPopUpService> popUpMock = new Mock <IPopUpService>(); //ActivityManager activityManagerMock.Setup(x => x.ActitvityProvider).Returns(activityProviderMock.Object); activityProviderMock.Setup(x => x.GetService(typeof(AbstractRunningActivity))).Returns(runningActivityMock.Object); activityProviderMock.Setup(x => x.GetService(typeof(AbstractStepActivity))).Returns(stepActivityMock.Object); //IDataBaseConnection Mock <IDataBaseConnection> mockDataBase = new Mock <IDataBaseConnection>(); List <DBEntry> entries = new List <DBEntry>(); mockDataBase.As <IDataBaseConnection>().Setup(x => x.GetMostRecentEntries(1)).Returns(entries); DateTime _dt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day); DBEntry _entryNew = new DBEntry(_dt, 10, 0, 0); mockDataBase.As <IDataBaseConnection>().Setup(x => x.SaveDBEntry(_entryNew)).Returns(1); //ServiceManager mockSingleton.Setup(x => x.GetService(typeof(IDataBaseConnection))).Returns(mockDataBase.Object); mockSingleton.Setup(x => x.GetService(typeof(IActivityManager))).Returns(activityManagerMock.Object); mockSingleton.Setup(x => x.GetService(typeof(IEarablesConnection))).Returns(connectionMock.Object); mockSingleton.Setup(x => x.GetService(typeof(IPopUpService))).Returns(popUpMock.Object); //Connection ScanningPopUpViewModel.IsConnected = true; connectionMock.As <IEarablesConnection>().Setup(x => x.StartSampling()); //ServiceProvider anlegen instance.SetValue(null, mockSingleton.Object); //Test StepModeViewModel viewModel = new StepModeViewModel(); viewModel.StartActivity(); Assert.Equal("--:--", viewModel.StepFrequency); viewModel.OnActivityDone(this, null); viewModel.OnActivityDone(this, null); viewModel.OnActivityDone(this, null); viewModel.OnRunningDone(this, new RunningEventArgs(true)); Assert.Equal(3, viewModel.StepCounter); Assert.True(viewModel.IsRunning); Assert.NotNull(viewModel.StepFrequency); Assert.Equal("Du läufst!", viewModel.StatusDisplay); viewModel.OnRunningDone(this, new RunningEventArgs(false)); Assert.False(viewModel.IsRunning); viewModel.StopActivity(); Assert.Equal(3, viewModel.StepCounter); viewModel.StartActivity(); Assert.Equal(0, viewModel.StepCounter); Assert.False(viewModel.IsRunning); }
public void UceniciController_Sacuvaj() { var grad = new List <Grad>() { new Grad { Id = 1, Naziv = "Beograd" }, new Grad { Id = 2, Naziv = "Novi Sad" } }.AsQueryable(); var smer = new List <Smer>() { new Smer { SmerID = 1, NazivSmera = "Mesar", Trajanje = 3 }, new Smer { SmerID = 2, NazivSmera = "Tehnicar", Trajanje = 6 } }.AsQueryable(); Ucenik uce = new Ucenik() { Adresa = "Adresa1", BrojTelefonaRoditelja = "064111222", DatumRodjenja = DateTime.Now, Ime = "Firas", Prezime = "Aburas", ImeMajke = "Mama", PrezimeMajke = "PrezimeMame", ImeOca = "Tata", PrezimeOca = "PrezimeTate", JedinstveniBroj = "1", JMBG = "1234567891012", MestoPrebivalista = "Beograd", MestoRodjenja = new Grad(), MestoRodjenjaId = 1, Odeljenje = new Odeljenje(), OdeljenjeId = 1, Razred = 1, Smer = new Smer(), SmerID = 1, UcenikID = 1, Vanredan = false }; var ucenik = new UcenikViewModel() { Ucenik = uce, Gradovi = grad, Smerovi = smer }; var mockSetGradovi = new Mock <DbSet <Grad> >(); mockSetGradovi.As <IQueryable <Grad> >().Setup(m => m.Provider).Returns(grad.Provider); mockSetGradovi.As <IQueryable <Grad> >().Setup(m => m.Expression).Returns(grad.Expression); mockSetGradovi.As <IQueryable <Grad> >().Setup(m => m.ElementType).Returns(grad.ElementType); mockSetGradovi.As <IQueryable <Grad> >().Setup(m => m.GetEnumerator()).Returns(grad.GetEnumerator()); var mockSetSmerovi = new Mock <DbSet <Smer> >(); mockSetSmerovi.As <IQueryable <Smer> >().Setup(m => m.Provider).Returns(smer.Provider); mockSetSmerovi.As <IQueryable <Smer> >().Setup(m => m.Expression).Returns(smer.Expression); mockSetSmerovi.As <IQueryable <Smer> >().Setup(m => m.ElementType).Returns(smer.ElementType); mockSetSmerovi.As <IQueryable <Smer> >().Setup(m => m.GetEnumerator()).Returns(smer.GetEnumerator()); var mockSet = new Mock <DbSet <Ucenik> >(); var mockContext = new Mock <ApplicationDbContext>(); mockContext.Setup(p => p.Ucenici).Returns(mockSet.Object); var services = new UceniciController(mockContext.Object); //services.Sacuvaj(ucenik); mockSet.Verify(p => p.Add(It.IsAny <Ucenik>()), Times.Once()); mockContext.Verify(p => p.SaveChanges(), Times.Once()); }
public void BeforeEach() { _webElementMock = new Mock <IWebElement>(); _findsByXPathMock = _webElementMock.As <IFindsByXPath>(); }
public async Task TestBlockedOperationCancel() { var copyOperation = new Mock <IInternalOperation>(); copyOperation .SetupGet(m => m.State) .Returns(OperationState.Blocked); var blockedOperation = copyOperation.As <ISelfBlockingOperation>(); blockedOperation .Setup(m => m.CurrentBlockedFile) .Returns((SourceName, DestinationName)); copyOperation .Setup(m => m.RunAsync(It.IsAny <CancellationToken>())) .Callback(() => { copyOperation.Raise(m => m.StateChanged += null, new OperationStateChangedEventArgs(OperationState.Blocked)); }); IReadOnlyList <OperationGroup> operationGroups = new List <OperationGroup> { new OperationGroup( new[] { copyOperation.Object }) }; _autoMocker.Use(operationGroups); var settings = new BinaryFileSystemOperationSettings( new string[] { }, new[] { SourceName }, new string[] { }, new[] { DestinationName }, new Dictionary <string, string> { [SourceName] = DestinationName }, new string[] { } ); _autoMocker.Use(new OperationInfo(OperationType.Copy, settings)); var operation = _autoMocker.CreateInstance <CompositeOperation>(); var taskCompletionSource = new TaskCompletionSource <bool>(); operation.Blocked += async(sender, args) => { if (operation.CurrentBlockedFile == (SourceName, DestinationName)) { await operation.CancelAsync(); taskCompletionSource.SetResult(true); } }; await operation.RunAsync(); var task = await Task.WhenAny(Task.Delay(500), taskCompletionSource.Task); if (task != taskCompletionSource.Task) { taskCompletionSource.SetResult(false); } var result = await taskCompletionSource.Task; Assert.True(result); } }
public void Setup() { _dbContextFacade = new Mock <IDBContextFacade>(MockBehavior.Loose); _dataConverter = new Mock <IDataConverter>(MockBehavior.Strict); _postFactory = new Mock <IPostFactory>(MockBehavior.Strict); _databaseImitation = new Mock <ApplicationDbContext>(MockBehavior.Loose); _dbsetMockPost = new Mock <DbSet <Post> >(MockBehavior.Strict); _dbsetMockUser = new Mock <DbSet <ApplicationUser> >(MockBehavior.Strict); _dbsetMockComment = new Mock <DbSet <Comment> >(MockBehavior.Strict); _dbsetMockLike = new Mock <DbSet <Like> >(MockBehavior.Strict); _dbsetMockReport = new Mock <DbSet <Report> >(MockBehavior.Strict); User = new ApplicationUser() { Id = "randomId", UserPosts = new List <Post>() }; post1 = new Post() { Id = 0, Author = "Shrekko", AuthorId = "randomId", Title = "MockPost", Content = "RandomContent", SubTitle = "Shrej", User = User, Likes = new List <Like>() }; post2 = new Post() { Id = 1, Author = "Shrekkoko", AuthorId = "randomId2", Title = "MockPost2", Content = "RandomContent2", SubTitle = "rORKA", User = User, Likes = new List <Like>() }; postList = new List <Post>(); postList.Add(post1); postList.Add(post2); comment1 = new Comment() { Id = 1, Author = "Shrekko", AuthorId = "randomId1", Content = "RandomContent1", User = User, Post = post1, Reports = new List <Report>() }; comment2 = new Comment() { Id = 2, Author = "Shrekkoko", AuthorId = "randomId2", Content = "RandomContent2", User = User, Post = post2, Reports = new List <Report>() }; positiveLike = new Like() { Id = 1, RatingType = RatingType.Positive, User = User, UserID = User.Id }; negativeLike = new Like() { Id = 2, RatingType = RatingType.Negative, User = User, UserID = User.Id }; likeList = new List <Like>(); likeList.Add(positiveLike); likeList.Add(negativeLike); report1 = new Report() { Id = 1, Comment = comment1, ReportText = "UMMAYAD", SenderName = User.UserName, CommentId = comment1.Id }; report2 = new Report() { Id = 2, Comment = comment2, ReportText = "BAD comment, indeed aga", SenderName = User.UserName, CommentId = comment2.Id }; reportList = new List <Report>(); reportList.Add(report1); reportList.Add(report2); userList = new List <ApplicationUser>(); userList.Add(User); commentList = new List <Comment>(); commentList.Add(comment1); commentList.Add(comment2); User.UserPosts = postList; _dbContextFacade.Setup(x => x.GetDBContext()).Returns(_databaseImitation.Object); _databaseImitation.Setup(x => x.Set <Post>()).Returns(_dbsetMockPost.Object); _dbsetMockPost.As <IQueryable <Post> >().Setup(m => m.Provider).Returns(postList.AsQueryable().Provider); _dbsetMockPost.As <IQueryable <Post> >().Setup(m => m.Expression).Returns(postList.AsQueryable().Expression); _dbsetMockPost.As <IQueryable <Post> >().Setup(m => m.ElementType).Returns(postList.AsQueryable().ElementType); _dbsetMockPost.As <IQueryable <Post> >().Setup(m => m.GetEnumerator()).Returns(postList.AsQueryable().GetEnumerator()); _dbsetMockPost.As <IEnumerable <Post> >().Setup(m => m.GetEnumerator()).Returns(postList.AsQueryable().GetEnumerator()); _dbsetMockComment.As <IQueryable <Comment> >().Setup(m => m.Provider).Returns(commentList.AsQueryable().Provider); _dbsetMockComment.As <IQueryable <Comment> >().Setup(m => m.Expression).Returns(commentList.AsQueryable().Expression); _dbsetMockComment.As <IQueryable <Comment> >().Setup(m => m.ElementType).Returns(commentList.AsQueryable().ElementType); _dbsetMockComment.As <IQueryable <Comment> >().Setup(m => m.GetEnumerator()).Returns(commentList.AsQueryable().GetEnumerator()); _dbsetMockComment.As <IEnumerable <Comment> >().Setup(m => m.GetEnumerator()).Returns(commentList.AsQueryable().GetEnumerator()); _dbsetMockReport.As <IQueryable <Report> >().Setup(m => m.Provider).Returns(reportList.AsQueryable().Provider); _dbsetMockReport.As <IQueryable <Report> >().Setup(m => m.Expression).Returns(reportList.AsQueryable().Expression); _dbsetMockReport.As <IQueryable <Report> >().Setup(m => m.ElementType).Returns(reportList.AsQueryable().ElementType); _dbsetMockReport.As <IQueryable <Report> >().Setup(m => m.GetEnumerator()).Returns(reportList.AsQueryable().GetEnumerator()); _dbsetMockReport.As <IEnumerable <Report> >().Setup(m => m.GetEnumerator()).Returns(reportList.AsQueryable().GetEnumerator()); _dbsetMockLike.As <IQueryable <Like> >().Setup(m => m.Provider).Returns(likeList.AsQueryable().Provider); _dbsetMockLike.As <IQueryable <Like> >().Setup(m => m.Expression).Returns(likeList.AsQueryable().Expression); _dbsetMockLike.As <IQueryable <Like> >().Setup(m => m.ElementType).Returns(likeList.AsQueryable().ElementType); _dbsetMockLike.As <IQueryable <Like> >().Setup(m => m.GetEnumerator()).Returns(likeList.AsQueryable().GetEnumerator()); _dbsetMockLike.As <IEnumerable <Like> >().Setup(m => m.GetEnumerator()).Returns(likeList.AsQueryable().GetEnumerator()); _dbsetMockUser.As <IQueryable <ApplicationUser> >().Setup(m => m.Provider).Returns(userList.AsQueryable().Provider); _dbsetMockUser.As <IQueryable <ApplicationUser> >().Setup(m => m.Expression).Returns(userList.AsQueryable().Expression); _dbsetMockUser.As <IQueryable <ApplicationUser> >().Setup(m => m.ElementType).Returns(userList.AsQueryable().ElementType); _dbsetMockUser.As <IQueryable <ApplicationUser> >().Setup(m => m.GetEnumerator()).Returns(userList.AsQueryable().GetEnumerator()); _dbsetMockUser.As <IEnumerable <ApplicationUser> >().Setup(m => m.GetEnumerator()).Returns(userList.AsQueryable().GetEnumerator()); _dbsetMockPost.Setup(m => m.Find(It.IsAny <object[]>())).Returns <object[]>(ids => postList.AsQueryable().FirstOrDefault(d => d.Id == (int)ids[0])); _dbsetMockComment.Setup(m => m.Find(It.IsAny <object[]>())).Returns <object[]>(ids => commentList.AsQueryable().FirstOrDefault(d => d.Id == (int)ids[0])); _dbsetMockReport.Setup(m => m.Find(It.IsAny <object[]>())).Returns <object[]>(ids => reportList.AsQueryable().FirstOrDefault(d => d.Id == (int)ids[0])); _dbsetMockLike.Setup(x => x.Remove(negativeLike)).Callback <Like>((entity) => likeList.Remove(entity)); _dbsetMockLike.Setup(x => x.Remove(positiveLike)).Callback <Like>((entity) => likeList.Remove(entity)); _dbsetMockPost.Setup(m => m.Remove(It.IsAny <Post>())).Callback <Post>((entity) => postList.Remove(entity)); _databaseImitation.Setup(x => x.Posts.Remove(It.IsAny <Post>())).Callback <Post>((entity) => postList.Remove(entity)); _databaseImitation.Setup(x => x.Posts).Returns(_dbsetMockPost.Object); _databaseImitation.Setup(x => x.Users).Returns(_dbsetMockUser.Object); _databaseImitation.Setup(x => x.Comments).Returns(_dbsetMockComment.Object); _databaseImitation.Setup(x => x.PostLikes).Returns(_dbsetMockLike.Object); _databaseImitation.Setup(x => x.Reports).Returns(_dbsetMockReport.Object); _postFactory.Setup(x => x.CreateLike(It.IsAny <int>(), It.IsAny <string>(), RatingType.Positive)).Returns(positiveLike); _postFactory.Setup(x => x.CreateLike(It.IsAny <int>(), It.IsAny <string>(), RatingType.Negative)) .Returns(negativeLike); _databaseImitation.Setup(x => x.PostLikes.Remove(negativeLike)).Callback <Like>((entity) => likeList.Remove(entity)); _databaseImitation.Setup(x => x.PostLikes.Remove(positiveLike)).Callback <Like>((entity) => likeList.Remove(entity)); _databaseImitation.Setup(x => x.SaveChanges()); _blogRepository = new BlogRepository(_dbContextFacade.Object, _dataConverter.Object, _postFactory.Object); }
public void GetAllTasks_MockDbSetTasksAndContext_AndGetAllUserTask() { //assign MiniAutoFixture miniAutoFixture = new MiniAutoFixture(); miniAutoFixture.Initialize(); User userSpecified = DbSetTools.CreateUser(1, miniAutoFixture); User user2 = DbSetTools.CreateUser(2, miniAutoFixture); User user3 = DbSetTools.CreateUser(3, miniAutoFixture); List <Task> tasksCollection = DbSetTools.CreateTaskList(1, userSpecified, 20, miniAutoFixture) .Concat(DbSetTools.CreateTaskList(21, user2, 10, miniAutoFixture)) .Concat(DbSetTools.CreateTaskList(31, user3, 10, miniAutoFixture)) .ToList(); IQueryable <Task> tasks = tasksCollection.AsQueryable(); List <User> userCollection = new User[] { userSpecified, user2, user3 }.ToList(); IQueryable <User> users = userCollection.AsQueryable(); var mockDbSetUser = new Mock <DbSet <User> >(); var mockDbSetTask = new Mock <DbSet <Task> >(); mockDbSetUser.As <IQueryable <User> >().Setup(m => m.Provider).Returns(users.Provider); mockDbSetUser.As <IQueryable <User> >().Setup(m => m.Expression).Returns(users.Expression); mockDbSetUser.As <IQueryable <User> >().Setup(m => m.ElementType).Returns(users.ElementType); mockDbSetUser.As <IQueryable <User> >().Setup(m => m.GetEnumerator()).Returns(users.GetEnumerator()); mockDbSetTask.As <IQueryable <Task> >().Setup(m => m.Provider).Returns(tasks.Provider); mockDbSetTask.As <IQueryable <Task> >().Setup(m => m.Expression).Returns(tasks.Expression); mockDbSetTask.As <IQueryable <Task> >().Setup(m => m.ElementType).Returns(tasks.ElementType); mockDbSetTask.As <IQueryable <Task> >().Setup(m => m.GetEnumerator()).Returns(tasks.GetEnumerator()); var mockContext = new Mock <OrganizerContext>(); mockContext.Setup(c => c.User).Returns(mockDbSetUser.Object); mockContext.Setup(c => c.Tasks).Returns(mockDbSetTask.Object); var logger = new Mock <ILogger <ViewRepository> >(); ViewRepository viewRepository = new ViewRepository(mockContext.Object, logger.Object); //action IEnumerable <TaskView> taskList = viewRepository.GetAllUserTask(userSpecified.Id); //assign IEnumerable <Task> tasksUser = tasks.Where(a => a.User.Id == userSpecified.Id); Assert.Equal(tasksUser.Count(), taskList.Count()); tasksUser.ToList().ForEach(task => { Assert.Equal ( taskList.Count ( taskView => taskView.Id == task.Id && taskView.Text == task.Text && taskView.Date == task.Date && taskView.Deleted == task.Deleted && taskView.Done == task.Done ), 1 ); } ); }
public void Ctor_Object_String_IBindingList(string dataMember) { PropertyDescriptor sortProperty = TypeDescriptor.GetProperties(typeof(DataClass))[0]; var syncRoot = new object(); var mockList = new Mock <IBindingList>(MockBehavior.Strict); mockList .Setup(p => p.Count) .Returns(0); mockList .Setup(p => p.AllowEdit) .Returns(false); mockList .Setup(p => p.AllowNew) .Returns(false); mockList .Setup(p => p.AllowRemove) .Returns(false); mockList .Setup(p => p.GetEnumerator()) .Returns(new List <int>().GetEnumerator()); mockList .Setup(p => p.IsFixedSize) .Returns(false); mockList .Setup(p => p.IsReadOnly) .Returns(false); mockList .Setup(p => p.IsSynchronized) .Returns(false); mockList .Setup(p => p.IsSorted) .Returns(true); mockList .Setup(p => p.SortDirection) .Returns(ListSortDirection.Descending); mockList .Setup(p => p.SortProperty) .Returns(sortProperty); mockList .Setup(p => p.SupportsChangeNotification) .Returns(false); mockList .Setup(p => p.SupportsSearching) .Returns(true); mockList .Setup(p => p.SupportsSorting) .Returns(true); mockList .Setup(p => p.SyncRoot) .Returns(syncRoot); var sortDescriptions = new ListSortDescriptionCollection(); var mockListView = mockList.As <IBindingListView>(); mockListView .Setup(p => p.SortDescriptions) .Returns(sortDescriptions); mockListView .Setup(p => p.SupportsAdvancedSorting) .Returns(true); mockListView .Setup(p => p.SupportsFiltering) .Returns(true); var source = new SubBindingSource(mockList.Object, dataMember); Assert.False(source.AllowEdit); Assert.False(source.AllowNew); Assert.False(source.AllowRemove); Assert.True(source.CanRaiseEvents); Assert.Null(source.Container); Assert.Empty(source); Assert.Equal(0, source.CurrencyManager.Count); Assert.Empty(source.CurrencyManager.Bindings); Assert.Same(source.CurrencyManager.Bindings, source.CurrencyManager.Bindings); Assert.Throws <IndexOutOfRangeException>(() => source.CurrencyManager.Current); Assert.True(source.CurrencyManager.IsBindingSuspended); Assert.Same(source, source.CurrencyManager.List); Assert.Equal(-1, source.CurrencyManager.Position); Assert.Same(source.CurrencyManager, source.CurrencyManager); Assert.Null(source.Current); Assert.Same(dataMember, source.DataMember); Assert.Same(mockList.Object, source.DataSource); Assert.False(source.DesignMode); Assert.NotNull(source.Events); Assert.Same(source.Events, source.Events); Assert.Null(source.Filter); Assert.True(source.IsBindingSuspended); Assert.False(source.IsFixedSize); Assert.False(source.IsReadOnly); Assert.True(source.IsSorted); Assert.False(source.IsSynchronized); Assert.Same(mockList.Object, source.List); Assert.True(source.RaiseListChangedEvents); Assert.Null(source.Site); Assert.Null(source.Sort); Assert.Same(sortDescriptions, source.SortDescriptions); Assert.Equal(ListSortDirection.Descending, source.SortDirection); Assert.Same(sortProperty, source.SortProperty); Assert.True(source.SupportsAdvancedSorting); Assert.True(source.SupportsChangeNotification); Assert.True(source.SupportsFiltering); Assert.True(source.SupportsSearching); Assert.True(source.SupportsSorting); Assert.Same(syncRoot, source.SyncRoot); }
private static Mock <DbSet <T> > CreateDbSetMock <T>(IQueryable <T> items) where T : class { var dbSetMock = new Mock <DbSet <T> >(); dbSetMock.As <IAsyncEnumerable <T> >() .Setup(x => x.GetAsyncEnumerator(default))
public void TestGetEmployee_ValidInput() { //Setup the required properties var rand = new Random(); var employeeId = rand.Next(1000); var firstName = "Test E"; var lastName = "Test E2"; var emailAddress = "*****@*****.**"; var employeeDTO = Mock.Of <EmployeeDTO>(e => e.EmailAddress == emailAddress && e.FirstName == firstName && e.LastName == lastName && e.Id == employeeId); var employees = new List <Employee> { new Employee { FirstName = "Test A", LastName = "Test A2", EmailAddress = "*****@*****.**", Id = rand.Next(1000) }, new Employee { FirstName = "Test B", LastName = "Test B2", EmailAddress = "*****@*****.**", Id = rand.Next(1000) }, new Employee { FirstName = "Test C", LastName = "Test C2", EmailAddress = "*****@*****.**", Id = rand.Next(1000) }, new Employee { FirstName = "Test D", LastName = "Test D2", EmailAddress = "*****@*****.**", Id = rand.Next(1000) }, new Employee { FirstName = firstName, LastName = lastName, EmailAddress = emailAddress, Id = employeeId } }.AsQueryable(); //Setup the Mock DbSet and its properties var employeeDbSetMock = new Mock <DbSet <Employee> >(); employeeDbSetMock.As <IQueryable <Employee> >().Setup(m => m.Provider).Returns(employees.Provider); employeeDbSetMock.As <IQueryable <Employee> >().Setup(m => m.Expression).Returns(employees.Expression); employeeDbSetMock.As <IQueryable <Employee> >().Setup(m => m.ElementType).Returns(employees.ElementType); employeeDbSetMock.As <IQueryable <Employee> >().Setup(m => m.GetEnumerator()).Returns(employees.GetEnumerator()); //Setup the Employees field for the _dbContextMock _dbContextMock.Setup(m => m.Employees).Returns(employeeDbSetMock.Object); //Setup the Mock for the _autoMapperMock.Setup(m => m.Map <EmployeeDTO>(It.IsNotNull <Employee>())).Returns(employeeDTO); //Call the method to test => GetEmployee() var employee = _employeeService.GetEmployee(employeeId); //Verify _dbContextMock method calls _dbContextMock.Verify(x => x.Employees, Times.Once); //Verify _autoMapperMock method calls _autoMapperMock.Verify(x => x.Map <EmployeeDTO>(It.IsAny <Employee>()), Times.Once); //Test the Returned Object Assert.IsNotNull(employee); Assert.AreEqual(employeeId, employee.Id); Assert.AreEqual(firstName, employee.FirstName); Assert.AreEqual(lastName, employee.LastName); Assert.AreEqual(emailAddress, employee.EmailAddress); }
public static Solution Create() { var mock = new Mock <Solution2>(); return(mock.As <Solution>().Object); }
private void TestBadAsForNonAbstractClass() { var mock = new Mock <BaseSampleClass>(); mock.As <OtherClass>(); }
public void SearchFollowersNoUserFoundTest() { var appSettingsClass = new AppSettings() { Secret = "1xNQ0brDZ6TwznGi9p58WRI2gfLJXcvq" }; IOptions <AppSettings> appSettings = Options.Create(appSettingsClass); var data = new List <UserModel> { new UserModel() { Id = 1, Token = "aa", Username = "******", Password = "******", Email = "@gmail" }.HashPassword(), new UserModel() { Id = 2, Token = "aaa", Username = "******", Password = "******", Email = "2@gmail" }.HashPassword() }.AsQueryable(); var mockSet = new Mock <DbSet <UserModel> >(); mockSet.As <IQueryable <UserModel> >().Setup(m => m.Provider).Returns(data.Provider); mockSet.As <IQueryable <UserModel> >().Setup(m => m.Expression).Returns(data.Expression); mockSet.As <IQueryable <UserModel> >().Setup(m => m.ElementType).Returns(data.ElementType); mockSet.As <IQueryable <UserModel> >().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator()); var followerData = new List <FollowerModel> { new FollowerModel() { FollowedId = 2, FollowerId = 1, Id = 1 } }.AsQueryable(); var followerMockSet = new Mock <DbSet <FollowerModel> >(); followerMockSet.As <IQueryable <FollowerModel> >().Setup(m => m.Provider).Returns(followerData.Provider); followerMockSet.As <IQueryable <FollowerModel> >().Setup(m => m.Expression).Returns(followerData.Expression); followerMockSet.As <IQueryable <FollowerModel> >().Setup(m => m.ElementType).Returns(followerData.ElementType); followerMockSet.As <IQueryable <FollowerModel> >().Setup(m => m.GetEnumerator()).Returns(followerData.GetEnumerator()); var options = new DbContextOptionsBuilder <MyDbContext>() .Options; var mockContext = new Mock <MyDbContext>(options); mockContext.Setup(x => x.Users).Returns(mockSet.Object); mockContext.Setup(x => x.Followers).Returns(followerMockSet.Object); mockContext.SetupProperty(x => x.Trips); mockContext.SetupProperty(x => x.PinPoints); var userService = new UserService(appSettings, mockContext.Object); var service = new AccountController(mockContext.Object, userService); var result = service.SearchFollowers("BB"); Assert.AreEqual(result.Result.Value, null); }
private void TestOkAsForInterface() { var mock = new Mock <BaseSampleClass>(); mock.As <ISampleInterface>(); }