public void Init() { Mock<ICustomerRepository<CustomerModel>> mockCustomerRepository = new Mock<ICustomerRepository<CustomerModel>>(); Mock<IEngineerRepository<EngineerModel>> mockEngineerRepository = new Mock<IEngineerRepository<EngineerModel>>(); Mock<IInstallationRepository<InstallationModel>> mockInstallationRepository = new Mock<IInstallationRepository<InstallationModel>>(); List<EngineerModel> engineers = new List<EngineerModel> { new EngineerModel {engineerid=0, firstname="Karl", lastname="Maier", password="******",email="*****@*****.**", username="******"} }; List<InstallationModel> installations = new List<InstallationModel> { new InstallationModel { installationid= 0, customerid=0, description="test", latitude=44, longitude=55, Measurement= new List<int>{0}, serialno="serial"} }; List<CustomerModel> customers = new List<CustomerModel> { new CustomerModel { customerid=0, engineerid=0, firstname="Anton", lastname="Huber", password="******",email="*****@*****.**", username="******", Installation=new List<int> {0}} }; mockCustomerRepository.Setup(mr => mr.GetAll()).Returns(customers); mockCustomerRepository.Setup(mr => mr.GetById(It.IsAny<int>())).Returns((int customerid) => customers.Where(customer => customer.customerid == customerid).Single()); mockCustomerRepository.Setup(mr => mr.Add(It.IsAny<CustomerModel>())).Callback((CustomerModel customer) => customers.Add(customer)); mockInstallationRepository.Setup(mr => mr.GetByCustomerId(It.IsAny<int>())).Returns((int customerid) => installations.Where(installation => installation.customerid == customerid).ToList<InstallationModel>()); mockInstallationRepository.Setup(mr => mr.Add(It.IsAny<InstallationModel>())).Callback((InstallationModel installation) => installations.Add(installation)); mockInstallationRepository.Setup(mr => mr.GetAll()).Returns(installations); mockEngineerRepository.Setup(mr => mr.GetMyCustomers(It.IsAny<int>())).Returns((int id) => customers.Where(customer => customer.engineerid == id).ToList<CustomerModel>()); this.mockcrepo = mockCustomerRepository.Object; this.mockirepo = mockInstallationRepository.Object; this.mockerepo = mockEngineerRepository.Object; }
/// <summary> /// Constructor /// </summary> public MoqTests() { // Create Products IList<Product> products = new List<Product> { new Product { ProductId = 1, Name = "C# Unleashed", Description = "Short description here", Price = 49.99 }, new Product { ProductId = 2, Name = "ASP.Net Unleashed", Description = "Short description here", Price = 59.99 }, new Product { ProductId = 3, Name = "Silverlight Unleashed", Description = "Short description here", Price = 29.99 } }; // Mock the Products Repository using Moq Mock<IProductRepository> mockProductRepository = new Mock<IProductRepository>(); // Return all the products mockProductRepository.Setup(mr => mr.FindAll()).Returns(products); // return a product by Id mockProductRepository.Setup(mr => mr.FindById(It.IsAny<int>())).Returns((int i) => products.Where(x => x.ProductId == i).Single()); // return a product by Name mockProductRepository.Setup(mr => mr.FindByName(It.IsAny<string>())).Returns((string s) => products.Where(x => x.Name == s).Single()); // Allows us to test saving a product mockProductRepository.Setup(mr => mr.Save(It.IsAny<Product>())).Returns( (Product target) => { DateTime now = DateTime.Now; if (target.ProductId.Equals(default(int))) { target.DateCreated = now; target.DateModified = now; target.ProductId = products.Count() + 1; products.Add(target); } else { var original = products.Where(q => q.ProductId == target.ProductId).Single(); if (original == null) { return false; } original.Name = target.Name; original.Price = target.Price; original.Description = target.Description; original.DateModified = now; } return true; }); // Complete the setup of our Mock Product Repository this.MockProductsRepository = mockProductRepository.Object; }
public static List<StudentDG> GetCateListTree(List<StudentDG> catelisttree) { foreach (var item in catelisttree) { var child = catelisttree.Where(t => t.ParenID == item.ID); if (child.Any()) item.ChildList = child.ToList(); } return catelisttree.Where(t => t.ParenID == 0).ToList(); }
public void GetWithTagsTest() { MongoDBLayer dblayer = new MongoDBLayer(); List<FormData> actual = new List<FormData>(); actual = dblayer.GetByTagAndContentId<FormData>(Guid.Parse("19c91d63-e3a2-4dae-bb3c-01efc0334b34"), "foo1"); Assert.IsNotNull(actual); Assert.IsTrue(actual.Count > 0); Assert.IsNotNull(actual.Where(x => x.Tags.Contains("foo1")).FirstOrDefault<FormData>()); Assert.AreEqual(actual.Where(x => x.Tags.Contains("foo1")).FirstOrDefault<FormData>().ContentId, Guid.Parse("19c91d63-e3a2-4dae-bb3c-01efc0334b34")); }
public ProductControllerTest() { // create some mock products to play with IList<Product> products = new List<Product> { new Product { ProductId = 1, ProductName = "Television", ProductDescription = "Sony", Price = 25000 }, new Product { ProductId = 2, ProductName = "Computer", ProductDescription = "Dell", Price = 20000 }, new Product { ProductId = 4, ProductName = "Table", ProductDescription = "Wooden", Price = 600 } }; // Mock the Products Repository using Moq Mock<IProductRepository> mockProductRepository = new Mock<IProductRepository>(); // Return all the products mockProductRepository.Setup(mr => mr.FindAll()).Returns(products); // return a product by Id mockProductRepository.Setup(mr => mr.FindById(It.IsAny<int>())).Returns((int i) => products.Where(x => x.ProductId == i).Single()); // return a product by Name mockProductRepository.Setup(mr => mr.FindByName(It.IsAny<string>())).Returns((string s) => products.Where(x => x.ProductName == s).Single()); // Allows us to test saving a product mockProductRepository.Setup(mr => mr.Save(It.IsAny<Product>())).Returns( (Product target) => { if (target.ProductId.Equals(default(int))) { target.ProductId = products.Max(q => q.ProductId) + 1; //target.ProductId = products.Count() + 1; products.Add(target); } else { var original = products.Where(q => q.ProductId == target.ProductId).SingleOrDefault(); if (original != null) { return false; } products.Add(target); } return true; }); // Complete the setup of our Mock Product Repository this.MockProductsRepository = mockProductRepository.Object; }
/// <summary>The create mock context.</summary> /// <returns>The <see cref="Mock" />.</returns> public static Mock<IDatabaseContext> CreateMockContext() { Mock<IDatabaseContext> contextMock = new Mock<IDatabaseContext>(); IQueryable<Region> regions = new List<Region> { new Region { Id = 1, CountryId = 1, Name = "England" }, new Region { Id = 2, CountryId = 1, Name = "Scotland" }, new Region { Id = 3, CountryId = 1, Name = "Wales" }, new Region { Id = 4, CountryId = 1, Name = "Northen Ireland" }, new Region { Id = 5, CountryId = 2, Name = "Queensland" }, new Region { Id = 6, CountryId = 2, Name = "Victoria" }, new Region { Id = 7, CountryId = 2, Name = "Tasmania" }, new Region { Id = 8, CountryId = 2, Name = "New South Wales" } }.AsQueryable(); IQueryable<Country> coutries = new List<Country> { new Country { Id = 1, Name = "United Kingdom", Regions = regions.Where(a => a.CountryId == 1).ToList() }, new Country { Id = 2, Name = "Australia", Regions = regions.Where(a => a.CountryId == 2).ToList() } }.AsQueryable(); foreach (Region region in regions) { region.Country = coutries.First(a => a.Id == region.CountryId); } Mock<IDbSet<Country>> countryMock = new Mock<IDbSet<Country>>(); countryMock.As<IQueryable<Country>>().Setup(m => m.Provider).Returns(coutries.Provider); countryMock.As<IQueryable<Country>>().Setup(m => m.Expression).Returns(coutries.Expression); countryMock.As<IQueryable<Country>>().Setup(m => m.ElementType).Returns(coutries.ElementType); countryMock.As<IQueryable<Country>>().Setup(m => m.GetEnumerator()).Returns(coutries.GetEnumerator()); Mock<IDbSet<Region>> regionMock = new Mock<IDbSet<Region>>(); regionMock.As<IQueryable<Region>>().Setup(m => m.Provider).Returns(regions.Provider); regionMock.As<IQueryable<Region>>().Setup(m => m.Expression).Returns(regions.Expression); regionMock.As<IQueryable<Region>>().Setup(m => m.ElementType).Returns(regions.ElementType); regionMock.As<IQueryable<Region>>().Setup(m => m.GetEnumerator()).Returns(regions.GetEnumerator()); contextMock.Setup(a => a.Countries).Returns(countryMock.Object); contextMock.Setup(a => a.Regions).Returns(regionMock.Object); // verify that the mocking is setup correctly List<Region> result = contextMock.Object.Countries.Include(a => a.Regions).SelectMany(a => a.Regions).ToList(); Assert.AreEqual(regions.Count(), result.Count); return contextMock; }
public void ObjectEventNotifierOutOfRangeTestMethod() { FileInfo _testDataFileInfo = new FileInfo(@"ModelsWithErrors\WrongEventNotifier.xml"); Assert.IsTrue(_testDataFileInfo.Exists); List<TraceMessage> _trace = new List<TraceMessage>(); int _diagnosticCounter = 0; IAddressSpaceContext _as = new AddressSpaceContext(z => TraceDiagnostic(z, _trace, ref _diagnosticCounter)); Assert.IsNotNull(_as); _as.ImportUANodeSet(_testDataFileInfo); Assert.AreEqual<int>(0, _trace.Where<TraceMessage>(x => x.BuildError.Focus != Focus.Diagnostic).Count<TraceMessage>()); _as.ValidateAndExportModel(m_NameSpace); Assert.AreEqual<int>(1, _trace.Where<TraceMessage>(x => x.BuildError.Focus != Focus.Diagnostic).Count<TraceMessage>()); }
public void NotSupportedFeature() { FileInfo _testDataFileInfo = new FileInfo(@"ModelsWithErrors\NotSupportedFeature.xml"); Assert.IsTrue(_testDataFileInfo.Exists); List<TraceMessage> _trace = new List<TraceMessage>(); int _diagnosticCounter = 0; IAddressSpaceContext _as = new AddressSpaceContext(z => TraceDiagnostic(z, _trace, ref _diagnosticCounter)); Assert.IsNotNull(_as); _as.ImportUANodeSet(_testDataFileInfo); Assert.AreEqual<int>(0, _trace.Where<TraceMessage>(x => x.BuildError.Focus != Focus.Diagnostic).Count<TraceMessage>()); _as.ValidateAndExportModel(m_NameSpace); Assert.AreEqual<int>(1, _trace.Where<TraceMessage>(x => x.BuildError.Focus != Focus.Diagnostic).Count<TraceMessage>()); Assert.AreEqual<int>(1, _trace.Where<TraceMessage>(x => x.BuildError.Identifier == "P0-0001010000").Count<TraceMessage>()); }
public void Initialize() { List<IUser> users = new List<IUser> { new User(198724), new User(9218) }; users = users.Where(x => x.EmployeeID == 198724).Select(usr => { usr.Name = "tatsumoto, takashi"; return usr; }).ToList(); users = users.Where(x => x.EmployeeID == 198724).Select(usr => { usr.NTLogin = "******"; return usr; }).ToList(); users = users.Where(x => x.EmployeeID == 198724).Select(usr => { usr.ManagerID = 9218; return usr; }).ToList(); //svc.Setup(x => x.getUser(It.IsAny<int>())).Returns((int empID) => { return users.Single(y => y.EmployeeID == empID); }); //svc.Setup(x => x.getAllUsers()).Returns(users); svc.Setup(x => x.getAllUsers()).Returns(users); }
public void Setup() { _board = new Mock<IBasicBoard>(); //0000000 //0111110 //0121210 //0111110 //0121110 //0111110 //0000000 var testBoard = new List<IBasicPolygon>(); for (int x = 0; x < 7; x++) { for (int y = 0; y < 7; y++) { if (y == 0 || y == 6 || x == 0 || x == 6) { var solid = new BasicPolygon(); solid.State = PolygonState.Solid; solid.Coordintes = new Point3d() { X = x, Y = y }; testBoard.Add(solid); } else { var empty = new BasicPolygon(); empty.State = PolygonState.Empty; empty.Coordintes = new Point3d() { X = x, Y = y }; testBoard.Add(empty); } } } var cellToFill = testBoard.Where(c => c.Coordintes.X == 2 && c.Coordintes.Y == 2).First(); cellToFill.State = PolygonState.Filled; cellToFill = testBoard.Where(c => c.Coordintes.X == 4 && c.Coordintes.Y == 4).First(); cellToFill.State = PolygonState.Filled; cellToFill = testBoard.Where(c => c.Coordintes.X == 2 && c.Coordintes.Y == 4).First(); cellToFill.State = PolygonState.Filled; _board.SetupGet(b => b.Cells).Returns(testBoard); _game = new Mock<ILonerGame>(); _game.SetupGet(g => g.Board).Returns(_board.Object); _rules = new StandardRules(); _rules.Game = _game.Object; }
public void ShorcikLinqTest() { List<ListLinq> lista = new List<ListLinq>(); lista.Add(new ListLinq() {Imie = "Rafal", Nazwisko = "Bedkowski", Wiek = 40}); lista.Add(new ListLinq() {Imie = "Mariusz", Nazwisko = "Mularczyk", Wiek = 16}); lista.Add(new ListLinq() {Imie = "Bartłomiej", Nazwisko = "Korcz", Wiek = 25}); lista.Add(new ListLinq() {Imie = "Adam", Nazwisko = "Ficek", Wiek = 33}); lista.Add(new ListLinq() {Imie = "Amelia", Nazwisko = "Dydko", Wiek = 46}); var counter = lista.Count; var wynik = lista.Where(x=>x.Imie.Equals("Rafal")); var latka = lista.Where(x => x.Wiek > 25); var next = lista.Average(x => x.Wiek); Console.ReadKey(); }
public void CaseInsensitiveComparison() { List<GitInstallation> list = new List<GitInstallation> { new GitInstallation(@"C:\Program Files (x86)\Git", KnownGitDistribution.GitForWindows32v1), new GitInstallation(@"C:\Program Files (x86)\Git", KnownGitDistribution.GitForWindows32v2), new GitInstallation(@"C:\Program Files\Git", KnownGitDistribution.GitForWindows32v1), new GitInstallation(@"C:\Program Files\Git", KnownGitDistribution.GitForWindows32v2), new GitInstallation(@"C:\Program Files\Git", KnownGitDistribution.GitForWindows64v2), // ToLower versions new GitInstallation(@"C:\Program Files (x86)\Git".ToLower(), KnownGitDistribution.GitForWindows32v1), new GitInstallation(@"C:\Program Files (x86)\Git".ToLower(), KnownGitDistribution.GitForWindows32v2), new GitInstallation(@"C:\Program Files\Git".ToLower(), KnownGitDistribution.GitForWindows32v1), new GitInstallation(@"C:\Program Files\Git".ToLower(), KnownGitDistribution.GitForWindows32v2), new GitInstallation(@"C:\Program Files\Git".ToLower(), KnownGitDistribution.GitForWindows64v2), // ToUpper versions new GitInstallation(@"C:\Program Files (x86)\Git".ToUpper(), KnownGitDistribution.GitForWindows32v1), new GitInstallation(@"C:\Program Files (x86)\Git".ToUpper(), KnownGitDistribution.GitForWindows32v2), new GitInstallation(@"C:\Program Files\Git".ToUpper(), KnownGitDistribution.GitForWindows32v1), new GitInstallation(@"C:\Program Files\Git".ToUpper(), KnownGitDistribution.GitForWindows32v2), new GitInstallation(@"C:\Program Files\Git".ToUpper(), KnownGitDistribution.GitForWindows64v2), }; HashSet<GitInstallation> set = new HashSet<GitInstallation>(list); Assert.AreEqual(15, list.Count); Assert.AreEqual(5, set.Count); Assert.AreEqual(6, list.Where(x => x.Version == KnownGitDistribution.GitForWindows32v1).Count()); Assert.AreEqual(6, list.Where(x => x.Version == KnownGitDistribution.GitForWindows32v2).Count()); Assert.AreEqual(3, list.Where(x => x.Version == KnownGitDistribution.GitForWindows64v2).Count()); Assert.AreEqual(2, set.Where(x => x.Version == KnownGitDistribution.GitForWindows32v1).Count()); Assert.AreEqual(2, set.Where(x => x.Version == KnownGitDistribution.GitForWindows32v2).Count()); Assert.AreEqual(1, set.Where(x => x.Version == KnownGitDistribution.GitForWindows64v2).Count()); foreach (var v in Enum.GetValues(typeof(KnownGitDistribution))) { KnownGitDistribution kgd = (KnownGitDistribution)v; var a = list.Where(x => x.Version == kgd); Assert.IsTrue(a.All(x => x != a.First() || GitInstallation.PathComparer.Equals(x.Cmd, a.First().Cmd))); Assert.IsTrue(a.All(x => x != a.First() || GitInstallation.PathComparer.Equals(x.Config, a.First().Config))); Assert.IsTrue(a.All(x => x != a.First() || GitInstallation.PathComparer.Equals(x.Git, a.First().Git))); Assert.IsTrue(a.All(x => x != a.First() || GitInstallation.PathComparer.Equals(x.Libexec, a.First().Libexec))); Assert.IsTrue(a.All(x => x != a.First() || GitInstallation.PathComparer.Equals(x.Sh, a.First().Sh))); } }
public void Data_on_child() { var nodes = new List<FakeNode>(); nodes.Add(new FakeNode() { Parent = "A", Child = "A1" }); var rights = new List<KeyValuePair<string, string>>(); rights.Add(new KeyValuePair<string, string>("A1", "1")); rights.Add(new KeyValuePair<string, string>("A1", "2")); var tree = TreeBuilder.Build<string, IEnumerable<string>, FakeNode>( nodes, x => x.Parent, x => x.Child, x => rights.Where(n => n.Key.Equals(x)).Select(v => v.Value)); tree.Count().Should().Be(1); var a = tree.FirstOrDefault(); a.Children.Count().Should().Be(1); var a1 = a.Children.First(); a1.Data.Should().NotBeNull(); a1.Data.Count().Should().Be(2); a1.Data.FirstOrDefault(x => x == "1").Should().NotBeNull(); a1.Data.FirstOrDefault(x => x == "2").Should().NotBeNull(); }
public void Can_Add_Order_Via_Controller() { //ARRANGE List<Order> orders = new List<Order>(); Mock<IOrderRepository> mockOrder = new Mock<IOrderRepository>(); mockOrder.Setup(m => m.AddOrder(It.IsAny<Order>())).Returns((Order order) => { if (orders.LastOrDefault() == null) { order.OrderID = 1; } else { order.OrderID = orders.Last().OrderID + 1; } orders.Add(order); return true; }); mockOrder.Setup(m => m.GetOrder(It.IsAny<int>())).Returns((int id) => { return orders.Where(o => o.OrderID == id).FirstOrDefault(); }); OrderController target = new OrderController(mockOrder.Object); //ACT target.Index(new Order { Address = "lalala st.", Name = "lala", OrderDate = DateTime.Now }); target.Index(new Order { Address = "dadada st.", Name = "dada", OrderDate = DateTime.Now }); //ASSERT Assert.IsNotNull(orders.Last()); Assert.AreEqual(orders.Last().Name, "dada"); Assert.AreEqual(orders.Last().OrderID, orders.First().OrderID + 1); }
public void test_that_given_a_repository_with_many_changesets_the_latest_changeset_is_returned_by_get() { // arrange var changes = new List<SpeakerChange> { new SpeakerChange() { Version = 1 }, new SpeakerChange() { Version = 1 }, new SpeakerChange() { Version = 2 } }; var mock = new Mock<ISpeakerChangeRepository>(); mock.Setup(m => m.GetLatest()).Returns(() => { int latestVersion = changes.Max(c => c.Version); return changes.Where(c => c.Version == latestVersion).ToList(); }); _container.Bind<ISpeakerChangeRepository>().ToConstant(mock.Object); // act var controller = (SpeakerChangeController)_container.Get<IHttpController>("SpeakerChange", new IParameter[0]); var result = controller.Get(); // assert Assert.AreNotEqual(0, result.Count()); }
private static void PrintSchedule(List<Employee> employees, List<Duty> duties) { var maxNameLength = employees.Max(x => x.Name.Length); duties = duties.OrderBy(x => x.Timeslot).ToList(); Debug.Write(new string(' ', maxNameLength + Padding)); Debug.Write(String.Join(" ", duties.Select(x => x.Timeslot))); Debug.WriteLine(""); foreach (var employee in employees) { Debug.Write(employee.Name.PadRight(maxNameLength + Padding)); foreach (var duty in duties) { if (duty.Employee.Equals(employee)) { Debug.Write("X"); } else { Debug.Write(" "); } Debug.Write(" "); } Debug.Write(" "); PrintStatistics(employee, duties.Where(x => Equals(x.Employee, employee)).ToList()); Debug.WriteLine(""); } }
private static void PrintStatistics(Employee employee, List<Duty> duties) { var empduties = duties.Where(x => x.Employee.Equals(employee)).ToList(); var weekCount = empduties.Count(x => x.Type == DutyType.Week); var weekendCount = empduties.Count(x => x.Type == DutyType.Weekend); Debug.Write(String.Format("week: {0} weekend: {1} score: {2}", weekCount, weekendCount, _scoringfunction.Calculate(duties))); }
public void TestComponentAbilityFiltering() { // targeted test data var provoke = new TestBattleAbility("Provoke", true, false, false); var fire = new TestBattleAbility("Fire", true, false, false); // Buffs test data var protect = new TestBattleAbility("Protect", true, true, true); var shell = new TestBattleAbility("Shell", true, true, true); // Enabled test data var water = new TestBattleAbility("Water", false, false, false); var testData = new List<TestBattleAbility> { provoke, protect, shell, fire, water }; // Create the desired outcome with water removed since // it won't be enabled. var desiredOutcome = testData.ToList(); desiredOutcome.Remove(water); var ordering = testData .Where(x => x.Enabled) .Where(x => x.IsBuff && x.HasEffectWore || !x.IsBuff); Assert.IsTrue(ordering.SequenceEqual(desiredOutcome)); }
public void test_that_get_returns_only_the_latest_changeset() { // arrange var changes = new List<SessionChange> { new SessionChange {ActionType = ChangeAction.Add, SessionId = 123, Version = 1}, new SessionChange { ActionType = ChangeAction.Modify, SessionId = 124, Key = "Title", Value = "new Title", Version = 1 }, new SessionChange {ActionType = ChangeAction.Delete, SessionId = 125, Version = 2}, }; var mock = new Mock<ISessionChangeRepository>(); mock.Setup(m => m.GetLatest()).Returns(() => { int latestVersion = changes.Max(s => s.Version); return changes.Where(sc => sc.Version == latestVersion).ToList(); }); _container.Bind<ISessionChangeRepository>().ToConstant(mock.Object); // act var controller = (SessionChangeController)_container.Get<IHttpController>("SessionChange", new IParameter[0]); var result = controller.Get(); // assert Assert.AreEqual(1, result.Count()); }
public void Edit_GET_InvalidUserId() { // arrange List<CompanyProfile> companies = new List<CompanyProfile>(); companies.Add(new CompanyProfile { Id = 1, CompanyName = "some company" }); companies.Add(new CompanyProfile { Id = 2, CompanyName = "some other company" }); UserProfile theUser = new UserProfile { CompanyId = 1, UserId = 1, Company = companies.Where(x => x.Id == 1).Single(), Email = "*****@*****.**", FirstName = "some", LastName = "fool", JobTitle = "nerf herder" }; Mock<IUserProfileServiceLayer> service = new Mock<IUserProfileServiceLayer>(); service.Setup(s => s.GetEnumerableCompanies()).Returns(companies); service.Setup(s => s.Get(theUser.UserId)).Returns(theUser); Mock<IWebSecurityWrapper> security = new Mock<IWebSecurityWrapper>(); Mock<IEmailSender> email = new Mock<IEmailSender>(); UserController controller = new UserController(service.Object, security.Object, email.Object); // act var result = controller.Edit(2) as ViewResult; // assert }
public void LinqFiltering() { var latestDate = new DateTime(2010, 6, 15); var posts = new List<Post> { new Post { PostedOn = new DateTime(1990, 12, 31) }, new Post { PostedOn = new DateTime(2000, 1, 1) }, new Post { PostedOn = latestDate } }; var cutoff = new DateTime(2000, 1, 1); var standardQuery = posts.Where(p => p.PostedOn > cutoff).ToList(); var extensionMethod = posts.PostedAfter(cutoff).ToList(); var expressionTree = posts.AsQueryable().Where(PostedAfter(cutoff)); Assert.AreEqual(standardQuery.Count(), 1); Assert.AreEqual(extensionMethod.Count(), 1); Assert.AreEqual(expressionTree.Count(), 1); Assert.AreEqual(standardQuery.First().PostedOn, latestDate); Assert.AreEqual(extensionMethod.First().PostedOn, latestDate); Assert.AreEqual(expressionTree.First().PostedOn, latestDate); }
public void TestWhereCopy_NullDestination_Throws() { IReadOnlySublist<List<int>, int> list = new List<int>().ToSublist(); IExpandableSublist<List<int>, int> destination = null; Func<int, bool> predicate = i => true; // always true list.Where(predicate).CopyTo(destination); }
public void TestAnonymousTypeWithLinq() { var personen = new List<Persoon> { new Persoon { Naam = "Manuel Riezebosch", Leeftijd = 31 }, new Persoon { Naam = "Ezra Riezebosch", Leeftijd = 3 } }; var result = personen. Where(p => p.Leeftijd > 25). Select(p => new { NaamEnLeeftijd = p.Naam + ", " + p.Leeftijd, p.Naam, Original = p }).ToList(); foreach (var item in result) { Console.WriteLine(item.NaamEnLeeftijd); } personen.Add(new Persoon { Naam = "Jeffrey Stuij", Leeftijd = 19 }); foreach (var item in result) { Console.WriteLine(item.NaamEnLeeftijd); } }
public void AircraftPictureManager_FindPicture_Searches_For_Pictures_In_Correct_Order() { _DirectoryCache.Object.Folder = @"c:\"; var existingFiles = new List<string>() { @"c:\ABC123.png", @"c:\ABC123.jpg", @"c:\ABC123.jpeg", @"c:\ABC123.bmp", @"c:\G-ABCD.png", @"c:\G-ABCD.jpg", @"c:\G-ABCD.jpeg", @"c:\G-ABCD.bmp", }; _DirectoryCache.Setup(c => c.FileExists(It.IsAny<string>())).Returns((string fn) => { return existingFiles.Where(ef => ef.Equals(fn, StringComparison.OrdinalIgnoreCase)).Any(); }); Assert.AreEqual(@"c:\ABC123.jpg", _PictureManager.FindPicture(_DirectoryCache.Object, "ABC123", "G-ABCD")); existingFiles.Remove(@"c:\ABC123.jpg"); Assert.AreEqual(@"c:\ABC123.jpeg", _PictureManager.FindPicture(_DirectoryCache.Object, "ABC123", "G-ABCD")); existingFiles.Remove(@"c:\ABC123.jpeg"); Assert.AreEqual(@"c:\ABC123.png", _PictureManager.FindPicture(_DirectoryCache.Object, "ABC123", "G-ABCD")); existingFiles.Remove(@"c:\ABC123.png"); Assert.AreEqual(@"c:\ABC123.bmp", _PictureManager.FindPicture(_DirectoryCache.Object, "ABC123", "G-ABCD")); existingFiles.Remove(@"c:\ABC123.bmp"); Assert.AreEqual(@"c:\G-ABCD.jpg", _PictureManager.FindPicture(_DirectoryCache.Object, "ABC123", "G-ABCD")); existingFiles.Remove(@"c:\G-ABCD.jpg"); Assert.AreEqual(@"c:\G-ABCD.jpeg", _PictureManager.FindPicture(_DirectoryCache.Object, "ABC123", "G-ABCD")); existingFiles.Remove(@"c:\G-ABCD.jpeg"); Assert.AreEqual(@"c:\G-ABCD.png", _PictureManager.FindPicture(_DirectoryCache.Object, "ABC123", "G-ABCD")); existingFiles.Remove(@"c:\G-ABCD.png"); Assert.AreEqual(@"c:\G-ABCD.bmp", _PictureManager.FindPicture(_DirectoryCache.Object, "ABC123", "G-ABCD")); }
private static bool ValidateNavigation(NavigationDiagram navigationConfiguration, List<Dialog> dialogs) { var unconvertedNavigations = from s in navigationConfiguration.States from su in s.Successors let c = GetStateWrappersCanNavigateTo(dialogs, s, su).Count() where (c > 0 && c < GetStateWrappers(dialogs, s).Count()) || (c == 0 && dialogs.Where(d => d.Initial == su).FirstOrDefault() == null) || (c == 0 && Transition.GetLink(s, su).CanNavigateBack) select s; var unconvertedInitialStates = from s in navigationConfiguration.States where s.Initial && dialogs.Where(d => d.Initial == s).FirstOrDefault() == null select s; return unconvertedNavigations.FirstOrDefault() == null && unconvertedInitialStates.FirstOrDefault() == null; }
public void AreAllNonEmptyStringsLongerThan5_ReturnsTrueWhenAllStringsSatisfy() { var stringData = new List<string> { null, "", "somethingLonger", "aaaaaaaa", "bbbbbbb", "something" }; var expected = stringData.Where(s => !string.IsNullOrEmpty(s)).All(s => s.Length > 5); var result = Ex2.AreAllNonEmptyStringsLongerThan5(stringData); result.Should().BeTrue(); }
public void AreAllNonEmptyStringsLongerThan5_ReturnsFalseWhenIncorrectStringExists() { var stringData = new List<string> {null, "", "somethingLonger", "aaaaaaaa", "bbbbbbb", "1234" , "something" }; var expected = stringData.Where(s => !string.IsNullOrEmpty(s)).All(s => s.Length > 5); var result = Ex2.AreAllNonEmptyStringsLongerThan5(stringData); result.Should().BeFalse(); }
public void GetStudentGradesList_ExistedInJournalStudent() { //Arrange int Id = 1; // student Id List<Teachers> teachers = new List<Teachers>() // All teachers list { new Teachers() { TeacherId = 1, Subject = "History" }, new Teachers() { TeacherId = 2, Subject = "Math" }, new Teachers() { TeacherId = 3, Subject = "Chemistry" } }; List<Teachers> freeTeachers = new List<Teachers>() // One teacher without students { new Teachers() { TeacherId = 3, Subject = "Chemistry" } }; List<Journal> journal = new List<Journal>() // Journal of grades, each teacher has two students { new Journal() { StudentId = 1, TeacherId = 1, Grade = 4, Teachers = teachers.Where(x=>x.TeacherId.Equals(1)).FirstOrDefault() }, new Journal() { StudentId = 1, TeacherId = 2, Grade = 5, Teachers = teachers.Where(x=>x.TeacherId.Equals(2)).FirstOrDefault() } }; bool expectedIsTeacher1 = true; // Teacher with Id=1 teaches that student bool expectedIsTeacher2 = true; // Teacher with Id=2 teaches that student bool expectedIsTeacher3 = false; // Teacher with Id=3 not teaches that student // Act List<StudentGradesModel> result = DBHelper.Instance.GetStudentGradesList(teachers, freeTeachers, journal, Id); bool actualIsTeacher1 = result .Where(x => x.StudentId.Equals(Id) && x.TeacherId.Equals(1)).ToList() .Select(x => x.IsTeacher).FirstOrDefault(); bool actualIsTeacher2 = result .Where(x => x.StudentId.Equals(Id) && x.TeacherId.Equals(2)).ToList() .Select(x => x.IsTeacher).FirstOrDefault(); bool actualIsTeacher3 = result .Where(x => x.StudentId.Equals(Id) && x.TeacherId.Equals(3)).ToList() .Select(x => x.IsTeacher).FirstOrDefault(); // Assert Assert.IsNotNull(result); Assert.AreEqual(3, result.Count); // Should return 3 records (2 teachers from journal and 1 free) Assert.AreEqual(expectedIsTeacher1, actualIsTeacher1); Assert.AreEqual(expectedIsTeacher2, actualIsTeacher2); Assert.AreEqual(expectedIsTeacher3, actualIsTeacher3); }
//public CommodityControllerTest() //{ // //TODO use the repository we prepared for testing the Commodity model //} public CommodityControllerTest() { // create some mock products to play with List<Commodity> testCommodities = new List<Commodity> { new Commodity { CommodityID = 1, Name = "Wheat",LongName = "",CommodityTypeID = 1, ParentID = null }, new Commodity { CommodityID = 5, Name = "Yellow Wheat",LongName = "",CommodityTypeID = 1, ParentID = 1 }, new Commodity { CommodityID = 6, Name = "Green Wheat",LongName = "",CommodityTypeID = 1, ParentID = 1 }, new Commodity { CommodityID = 3, Name = "CSB",LongName = "",CommodityTypeID = 1, ParentID = null }, new Commodity { CommodityID = 8, Name = "Beans",LongName = "",CommodityTypeID = 1, ParentID = 3 }, }; // Mock the AdminUNit Repository using Moq Mock<IUnitOfWork> mockCommodityRepository = new Mock<IUnitOfWork>(); // Return all the Commodities mockCommodityRepository.Setup(mr => mr.Commodity.GetAll()).Returns(testCommodities); // return a Commodity by CommodityId mockCommodityRepository.Setup(mr => mr.Commodity.FindById( It.IsAny<int>())).Returns((int i) => testCommodities.Where(x => x.CommodityID == i).SingleOrDefault()); //return all parent commodities mockCommodityRepository.Setup(mr => mr.Commodity.GetAllParents()) .Returns(testCommodities.Where(x => x.ParentID == null).ToList()); //return all children commodities mockCommodityRepository.Setup(mr => mr.Commodity.GetAllSubCommodities()) .Returns(testCommodities.Where(x => x.ParentID != null).ToList()); //return a commodity by it's name mockCommodityRepository.Setup(mr => mr.Commodity.GetCommodityByName( It.IsAny<string>())).Returns((string i) => testCommodities.Where(x => x.Name == i).SingleOrDefault()); //retun all commodities by thier parent mockCommodityRepository.Setup(mr => mr.Commodity.GetAllSubCommoditiesByParantId( It.IsAny<int>())).Returns((int i) => testCommodities.Where(x => x.ParentID == i).ToList()); //return a commodity by it's name mockCommodityRepository.Setup(mr => mr.CommodityType.GetAll( )).Returns(new List<BLL.CommodityType>()); this.MockCommodityRepository = mockCommodityRepository.Object; }
public void GetNonNullNorEmptyStrings_ReturnsCorrectResult() { var stringData = new List<string> {null, "", "test", "test2", "", "something", null, " "}; var expected = stringData.Where(s => !string.IsNullOrEmpty(s)); var result = Ex1.GetNonNullNorEmptyStrings(stringData); result.ShouldAllBeEquivalentTo(expected); }