コード例 #1
1
ファイル: StaffTest.cs プロジェクト: hlim29/ENET_Care_A1
 /**
  * Create Mock Staff Object for test purposes
  */
 private Staff createStaffMock()
 {
     var dummyStaff = new Moq.Mock<Staff>();
     dummyStaff.SetupProperty(staff => staff.FirstName, "First")
                 .SetupProperty(staff => staff.LastName, "Last")
                 .SetupProperty(staff => staff.Role, "Agent")
                 .SetupProperty(staff => staff.DistributionCentre, new DistributionCentre());
     return dummyStaff.Object;
 }
コード例 #2
0
        public void Test_CtorWithAd()
        {
            // Given
            SailingBoatAd ad = new SailingBoatAd
            {
                Title = "title",
                SailingBoatType = new Bea.Domain.Reference.SailingBoatType { Label = "type" },
                HullType = new Bea.Domain.Reference.SailingBoatHullType { Label = "hull" },
                Year = 2012,
                Length = 15.75000,
                City = new City(),
                CreatedBy = new User()
            };

            var helperMock = new Moq.Mock<IHelperService>();
            helperMock.Setup(x => x.GetCulture()).Returns(new System.Globalization.CultureInfo("Fr"));

            // When
            SailingBoatAdDetailsModel actual = new SailingBoatAdDetailsModel(ad, helperMock.Object);

            // Then
            Assert.AreEqual(ad.Title, actual.Title);
            Assert.AreEqual(ad.SailingBoatType.Label, actual.BoatType);
            Assert.AreEqual(ad.HullType.Label, actual.HullType);
            Assert.AreEqual(ad.Year, actual.Year);
            Assert.AreEqual("15,75 Mtr", actual.Length);
        }
コード例 #3
0
        public void Can_Remove_Product_From_Cart()
        {
            // Arrange: Set up a mock repository with two products
            var mockProductsRepos = new Moq.Mock<IProductsRepository>();
            var products = new System.Collections.Generic.List<Product> {
            new Product { ProductID = 14, Name = "Much Ado About Nothing" },
            new Product { ProductID = 27, Name = "The Comedy of Errors" },
            };
            mockProductsRepos.Setup(x => x.Products)
                         .Returns(products.AsQueryable());
            var cart = new Cart();
            cart.AddItem(products[1], 2); // 2x Comedy of Errors
            cart.AddItem(products[0], 3); // 3x Much Ado
            var controller = new CartController(mockProductsRepos.Object, null);

            // Act: Try removing Much Ado
            RedirectToRouteResult result =
            controller.RemoveFromCart(cart, 14, "someReturnUrl");

            // Assert
            Assert.AreEqual(1, cart.Lines.Count);
            Assert.AreEqual("The Comedy of Errors", cart.Lines[0].Product.Name);
            Assert.AreEqual(2, cart.Lines[0].Quantity);

            // Check that the visitor was redirected to the cart display screen
            Assert.AreEqual("Index", result.RouteValues["action"]);
            Assert.AreEqual("someReturnUrl", result.RouteValues["returnUrl"]);
        }
コード例 #4
0
        ShoppingCart.Web.Mvc.Controllers.CartController CreateCartController()
        {
            var mock = new Moq.Mock<ControllerContext>();

            var cartRepository = new Services.MockCartRepository();
            var cartService = new ShoppingCart.Web.Mvc.Services.CartService(cartRepository);

            var product = new Moq.Mock<Model.IProduct>();
            product.Setup(i => i.Code).Returns("xxx");
            product.Setup(i => i.Packaging).Returns(1);
            product.Setup(i => i.SaleUnitValue).Returns(1);
            product.Setup(i => i.Title).Returns("product 1");

            var catalogService = new Moq.Mock<Mvc.Services.ICatalogService>();
            catalogService.Setup(i => i.GetProductByCode("xxx")).Returns(product.Object);
            catalogService.Setup(i => i.GetPriceByProduct(product.Object)).Returns(new ShoppingCart.Web.Mvc.Model.Price(10.0, 0.196));

            var controller = new ShoppingCart.Web.Mvc.Controllers.CartController(
                cartService,
                catalogService.Object);

            controller.ControllerContext = mock.Object;

            return controller;
        }
コード例 #5
0
        public void Produces_Home_Plus_NaLink_Object_For_Each_Distinct_Category()
        {
            // Подготовка
            IQueryable<Product> products = new[] {
                new Product { Name="A", Category="Animal" },
                new Product { Name="B", Category="Vegetable" },
                new Product { Name="C", Category="Mineral" },
                new Product { Name="D", Category="Vegetable" },
                new Product { Name="E",Category="Animal" }
            }.AsQueryable();
            var mockProductRepository = new Moq.Mock<IProductsRepository>();
            mockProductRepository.Setup(x => x.Products).Returns(products);
            var controller = new NavController(mockProductRepository.Object);

            // Действие
            ViewResult result = controller.Menu(null);

            var links = ((IEnumerable<NavLink>)result.ViewData.Model).ToList();
            Assert.AreEqual(4, links.Count);
            Assert.AreEqual("All", links[0].Text);
            Assert.AreEqual("Animal", links[1].Text);
            Assert.AreEqual("Mineral", links[2].Text);
            Assert.AreEqual("Vegetable", links[3].Text);
            foreach(var link in links)
            {
                Assert.AreEqual("Products", link.RouteValues["controller"]);
                Assert.AreEqual("List", link.RouteValues["action"]);
                Assert.AreEqual(1, link.RouteValues["page"]);
                if (links.IndexOf(link) == 0)
                    Assert.IsNull(link.RouteValues["category"]);
                else
                    Assert.AreEqual(link.Text, link.RouteValues["category"]);
            }
        }
コード例 #6
0
        public void AddColumn_Adds_New_Column_When_Cols_And_Rows_Do_Exist(string colName, Type colType, string[] colNames, Type[] colTypes)
        {
            //Arrange
            int rowCount = 2;
            var mockNet = new Moq.Mock<INetwork>();
            var table = new DataAttributeTable<IEdge>();
            table.Network = mockNet.Object;
            for (int i = 0; i < colNames.Length; i++)
                table.Columns.Add(colNames[i], colTypes[i]);

            DataRow row = table.NewRow();
            table.Rows.Add(row);
            row = table.NewRow();
            table.Rows.Add(row);

            Assert.Equal(table.Columns.Count, colNames.Length);

            int index = colNames.Length;

            //Act
            table.AddColumn(colName, colType);

            //Assert
            Assert.Equal(table.Columns.Count, colNames.Length + 1);
            Assert.Equal(table.Columns[index].ColumnName, colName);
            Assert.Equal(table.Columns[index].DataType, colType);
            Assert.Equal(table.Rows.Count, rowCount);
        }
コード例 #7
0
        public void AddJob_Stores_the_Given_Job()
        {
            var job = new Moq.Mock<IJob>();
            _testObject.AddJob(job.Object);

            Assert.IsTrue(_testObject.GetJobs().Contains(job.Object));
        }
コード例 #8
0
ファイル: AdServicesTest.cs プロジェクト: bea-project/bea-web
        public void GetAdPicturesFromModel_2Pictures_FetchThemFromRepoAndSetFirstAsMainImage()
        {
            // Given
            BaseAd ad = new Ad();
            String images = "b9da8b1e-aa77-401b-84e0-a1290130b7b7;b9da8b1e-aa77-401b-84e0-a1290130b999;";

            AdImage img1 = new AdImage() { Id = Guid.Parse("b9da8b1e-aa77-401b-84e0-a1290130b7b7") };
            AdImage img2 = new AdImage() { Id = Guid.Parse("b9da8b1e-aa77-401b-84e0-a1290130b999") };

            var repoMock = new Moq.Mock<IRepository>();
            repoMock.Setup(x => x.Get<AdImage>(Guid.Parse("b9da8b1e-aa77-401b-84e0-a1290130b7b7"))).Returns(img1);
            repoMock.Setup(x => x.Get<AdImage>(Guid.Parse("b9da8b1e-aa77-401b-84e0-a1290130b999"))).Returns(img2);

            AdServices service = new AdServices(null, repoMock.Object, null);

            // When
            BaseAd result = service.GetAdPicturesFromModel(ad, images);

            // Then
            Assert.AreEqual(ad, result);
            Assert.AreEqual(2, ad.Images.Count);
            Assert.AreEqual("b9da8b1e-aa77-401b-84e0-a1290130b7b7", ad.Images[0].Id.ToString());
            Assert.AreEqual(ad, ad.Images[0].BaseAd);
            Assert.IsTrue(ad.Images[0].IsPrimary);
            Assert.AreEqual("b9da8b1e-aa77-401b-84e0-a1290130b999", ad.Images[1].Id.ToString());
            Assert.AreEqual(ad, ad.Images[1].BaseAd);
            Assert.IsFalse(ad.Images[1].IsPrimary);
        }
コード例 #9
0
        public void GetAdDetails_AdExists_GetAdFromRepoAndReturnAdModel()
        {
            // Given
            Ad ad = new Ad() { Id = 17 };
            ad.CreationDate = new DateTime(2012, 02, 18);
            ad.CreatedBy = new User { Firstname = "Michel" };
            ad.City = new City { Label = "Ville" };

            var repoMock = new Moq.Mock<IRepository>();
            repoMock.Setup(x => x.Get<BaseAd>(17)).Returns(ad as BaseAd);

            var adRepoMock = new Moq.Mock<IAdRepository>();
            adRepoMock.Setup(r => r.GetAdType(17)).Returns(AdTypeEnum.Ad);
            adRepoMock.Setup(r => r.GetAdById<Ad>(17)).Returns(ad);

            var helperMock = new Moq.Mock<IHelperService>();
            helperMock.Setup(s => s.GetCurrentDateTime()).Returns(new DateTime(2012, 02, 20));

            AdDetailsServices service = new AdDetailsServices(adRepoMock.Object, helperMock.Object);

            // When
            AdDetailsModel actual = service.GetAdDetails(17);

            // Then
            Assert.AreEqual(17, actual.AdId);
        }
コード例 #10
0
        public void TestSimple_2()
        {
            var facts = new List<NullableFact>();
            facts.Add(new NullableFact() { ProductId = null, GeographyId = null, SalesComponentId = null, TimeId = 1, Value = 100 });

            var products = new Moq.Mock<IHierarchy>();
            var geographies = new Moq.Mock<IHierarchy>();
            var causals = new Moq.Mock<IHierarchy>();
            var periods = new Moq.Mock<IHierarchy>();

            Expression<Func<IHierarchy, IEnumerable<short>>> anyInt = p => p.GetParents(Moq.It.IsAny<short>());
            var result = new List<short> { 1 };
            products.Setup(anyInt).Returns(result);
            geographies.Setup(anyInt).Returns(result);
            causals.Setup(anyInt).Returns(result);
            periods.Setup(anyInt).Returns(result);

            Expression<Func<IHierarchy, bool>> allRelationships = p => p.RelationExists(Moq.It.IsAny<short>(), Moq.It.IsAny<short>());
            products.Setup(allRelationships).Returns(true);
            geographies.Setup(allRelationships).Returns(true);
            causals.Setup(allRelationships).Returns(true);
            periods.Setup(allRelationships).Returns(true);

            //, Hierarchy products, Hierarchy geographies, Hierarchy causals, Hierarchy periods

            var lookup = new FactLookup(facts, products.Object, geographies.Object, causals.Object, periods.Object);

            Assert.AreEqual(100, lookup.GetParent(0, 0, 0, 1));
            Assert.AreEqual(100, lookup.GetParent(1, 1, 1, 1));
            Assert.AreEqual(100, lookup.GetParent(2, 2, 2, 1));
        }
コード例 #11
0
ファイル: TestBase.cs プロジェクト: njmube/SIQPOS
            public static void Initialize()
            {
                IAccountRepository accRepo = new Moq.Mock<IAccountRepository>().Object;
                ISessionRepository sessionRepo = new Moq.Mock<ISessionRepository>().Object;
                IPOSSettingRepository posSettingRepo = new Moq.Mock<IPOSSettingRepository>().Object;
                Moq.Mock<IProductRepository> productRepo = new Moq.Mock<IProductRepository>();
                product_1 = new Product(Guid.NewGuid(), "Product ABC", "001", "001", 2000);
                productRepo.Setup(i => i.GetByBarcodeOrCode("001")).Returns(product_1);

                Moq.Mock<ICompanyProfileRepository> cpRepo = new Moq.Mock<ICompanyProfileRepository>();
                cpRepo.Setup(i => i.Get()).Returns(new CompanyProfile("*****@*****.**", "123", "Toko Dny", "Diamond Palace", null));

                AutoNumber autoNumber = new AutoNumber("*****@*****.**", "123", DateTime.Now);
                Moq.Mock<IAutoNumberRepository> autoNumberRepo = new Moq.Mock<IAutoNumberRepository>();
                autoNumberRepo.Setup(i => i.Get(DateTime.Now)).Returns(autoNumber);

                var sessionHolder = new SessionHolder();
                ObjectFactory.Initialize(i =>
                {
                    i.For<IAccountRepository>().Use(accRepo);
                    i.For<ISessionRepository>().Use(sessionRepo);
                    i.For<ICompanyProfileRepository>().Use(cpRepo.Object);
                    i.For<SessionService>().Use<SessionService>();
                    i.For<ShoppingCartService>().Use<ShoppingCartService>();
                    i.ForSingletonOf<SessionHolder>().Use<SessionHolder>();
                    i.For<IProductRepository>().Use(productRepo.Object);
                    i.For<IPOSSettingRepository>().Use(posSettingRepo);
                    i.ForSingletonOf<SessionHolder>().Use(sessionHolder);
                    i.ForSingletonOf<IShoppingCartSingleton>().Use(sessionHolder);
                    i.For<IAutoNumberRepository>().Use(autoNumberRepo.Object);
                    i.For<AutoNumberGenerator>().Use<AutoNumberGenerator>();
                });
            }
コード例 #12
0
        public void tewwet()
        {
            var productRepository = new Moq.Mock<IProductRepository>();
            productRepository.Setup(x => x.Get())
                             .Returns(new[]
                                          {
                                              new Product()
                                                  {
                                                      ID = 1,
                                                      Title = "iPad",
                                                      Description = "Fruit based tablet",
                                                      UnitPrice = 450
                                                  },
                                              new Product()
                                                  {
                                                      ID = 2,
                                                      Title = "iPhone",
                                                      Description = "Fruit based phone",
                                                      UnitPrice = 500
                                                  }
                                          });

            var homeController = new HomeController(productRepository.Object);

            var result = homeController.Index() as ViewResult;

            Assert.NotNull(result.Model);
        }
コード例 #13
0
        public void SpamRequestAd_AdExists_SaveSpamRequest()
        {
            // Given
            var adRepoMock = new Moq.Mock<IAdRepository>();
            adRepoMock.Setup(x => x.CanDeleteAd(7)).Returns(true);

            var repoMock = new Moq.Mock<IRepository>();
            repoMock.Setup(x => x.Get<SpamAdType>(3)).Returns(new SpamAdType() { Id = 3 });

            var hSMock = new Moq.Mock<IHelperService>();
            hSMock.Setup(x => x.GetCurrentDateTime()).Returns(new DateTime(2013, 05, 17, 6, 7, 22));

            SpamAdRequestModel model = new SpamAdRequestModel();
            model.AdId = 7;
            model.Description = "description";
            model.RequestorEmail = "*****@*****.**";
            model.SelectedSpamAdTypeId = 3;

            SpamAdServices service = new SpamAdServices(adRepoMock.Object, repoMock.Object, hSMock.Object);

            // When
            SpamAdRequestModel result = service.SpamRequestAd(model);

            // Then
            Assert.IsFalse(result.CanSignal);
            Assert.AreEqual("Votre signalement a correctement été transmis. Merci de votre précieuse aide dans la chasse aux mauvaises annonces !", result.InfoMessage);

            repoMock.Verify(x => x.Save(Moq.It.Is<SpamAdRequest>(b =>
                b.Description == model.Description
                && b.RequestDate == new DateTime(2013, 05, 17, 6, 7, 22)
                && b.RequestorEmailAddress == model.RequestorEmail
                && b.SpamType.Id == 3)));
        }
コード例 #14
0
        public void Can_Remove_Product_From_Cart()
        {
            // Подготовка
            var mockProductsRepository = new Moq.Mock<IProductsRepository>();
            var products = new List<Product>()
            {
                new Product {ProductID=14, Name="Much Ado About Nothing" },
                new Product {ProductID=27, Name="The Comedy of Errors" }
            };
            mockProductsRepository.Setup(x => x.Products)
                                  .Returns(products.AsQueryable());
            var cart = new Cart();
            var controller = new CartController(mockProductsRepository.Object, null);
            controller.AddToCart(cart, 14, "someReturnUrl");
            controller.AddToCart(cart, 27, "someReturnUrl");
            Assert.AreEqual(2, cart.Lines.Count);
            // Действие
            RedirectToRouteResult result =
                controller.RemoveFromCart(cart, 14, "someReturnUrl");
            // Утверждение
            Assert.AreEqual(1, cart.Lines.Count);
            Assert.AreEqual(27, cart.Lines[0].Product.ProductID);

            Assert.AreEqual("Index", result.RouteValues["action"]);
            Assert.AreEqual("someReturnUrl", result.RouteValues["returnUrl"]);
        }
コード例 #15
0
        private void TestRoute(string url, object expectedValues)
        {
            // Arrange: Prepare the route collection and a mock request context
            RouteCollection routes = new RouteCollection();
            MvcApplication.RegisterRoutes(routes);
            var mockHttpContext = new Moq.Mock<HttpContextBase>();
            var mockRequest = new Moq.Mock<HttpRequestBase>();
            mockHttpContext.Setup(x => x.Request).Returns(mockRequest.Object);
            mockRequest.Setup(x => x.AppRelativeCurrentExecutionFilePath).Returns(url);

            // Act: Get the mapped route
            RouteData routeData = routes.GetRouteData(mockHttpContext.Object);

            // Assert: Test the route values against expectations
            Assert.IsNotNull(routeData);
            var expectedDict = new RouteValueDictionary(expectedValues);
            foreach (var expectedVal in expectedDict)
            {
                if (expectedVal.Value == null)
                    Assert.IsNull(routeData.Values[expectedVal.Key]);
                else
                    Assert.AreEqual(expectedVal.Value.ToString(),
                                    routeData.Values[expectedVal.Key].ToString());
            }
        }
コード例 #16
0
        private void TestRoute(string url, object expectedValues)
        {
            // Подготовка
            RouteCollection routes = new RouteCollection();
            RouteConfig.RegisterRoutes(routes);
            var mockHttpContext = new Moq.Mock<HttpContextBase>();
            var mockRequest = new Moq.Mock<HttpRequestBase>();
            mockHttpContext.Setup(x => x.Request).Returns(mockRequest.Object);
            mockRequest.Setup(x => x.AppRelativeCurrentExecutionFilePath).Returns(url);

            // Действие
            RouteData routeData = routes.GetRouteData(mockHttpContext.Object);

            // Утверждение
            Assert.IsNotNull(routeData);
            var expectedDist = new RouteValueDictionary(expectedValues);
            foreach (var expectedVal in expectedDist)
            {
                if (expectedVal.Value == null)
                    Assert.IsNull(routeData.Values[expectedVal.Key]);
                else
                    Assert.AreEqual(expectedVal.Value.ToString(),
                                    routeData.Values[expectedVal.Key].ToString());
            }
        }
コード例 #17
0
        public void ConcreteFactLookup_GlobalFact()
        {
            var facts = new List<ConcreteFact>();
            facts.Add(new ConcreteFact() { ProductId = 2, GeographyId = 2, SalesComponentId = 2, TimeId = 1, Value = 100 });
            facts.Add(new ConcreteFact() { ProductId = 3, GeographyId = 3, SalesComponentId = 3, TimeId = 1, Value = 100 });

            var products = new Moq.Mock<IHierarchy>();
            var geographies = new Moq.Mock<IHierarchy>();
            var causals = new Moq.Mock<IHierarchy>();
            var periods = new Moq.Mock<IHierarchy>();

            Expression<Func<IHierarchy, IEnumerable<short>>> anyInt = p => p.GetChildren(Moq.It.IsAny<short>());
            var result = new List<short> { 2, 3 };
            products.Setup(anyInt).Returns(result);
            geographies.Setup(anyInt).Returns(result);
            causals.Setup(anyInt).Returns(result);
            periods.Setup(anyInt).Returns(result);

            Expression<Func<IHierarchy, bool>> relation = h => h.RelationExists(Moq.It.IsAny<short>(), Moq.It.IsAny<short>());
            products.Setup(relation).Returns(true);
            geographies.Setup(relation).Returns(true);
            causals.Setup(relation).Returns(true);
            periods.Setup(relation).Returns(true);

            //, Hierarchy products, Hierarchy geographies, Hierarchy causals, Hierarchy periods

            var lookup = new ConcreteFactLookup(facts, products.Object, geographies.Object, causals.Object, periods.Object);

            Assert.AreEqual(200, lookup.SumChildren(1, 1, 1, 1));
        }
コード例 #18
0
		public void Setup()
		{
			var library = new Moq.Mock<CollectionSettings>();
			library.SetupGet(x => x.IsSourceCollection).Returns(false);
			library.SetupGet(x => x.Language2Iso639Code).Returns("en");
			library.SetupGet(x => x.Language1Iso639Code).Returns("xyz");
			library.SetupGet(x => x.XMatterPackName).Returns("Factory");

			ErrorReport.IsOkToInteractWithUser = false;
			_fileLocator = new FileLocator(new string[]
											{
												//FileLocator.GetDirectoryDistributedWithApplication( "factoryCollections"),
												BloomFileLocator.GetFactoryBookTemplateDirectory("Basic Book"),
												BloomFileLocator.GetFactoryBookTemplateDirectory("Wall Calendar"),
												FileLocator.GetDirectoryDistributedWithApplication( BloomFileLocator.BrowserRoot),
												BloomFileLocator.GetBrowserDirectory("bookLayout"),
												BloomFileLocator.GetBrowserDirectory("bookEdit","css"),
												BloomFileLocator.GetInstalledXMatterDirectory()
											});

			var projectFolder = new TemporaryFolder("BookStarterTests_ProjectCollection");
			var collectionSettings = new CollectionSettings(Path.Combine(projectFolder.Path, "test.bloomCollection"));

			_starter = new BookStarter(_fileLocator, dir => new BookStorage(dir, _fileLocator, new BookRenamedEvent(), collectionSettings), library.Object);
			_shellCollectionFolder = new TemporaryFolder("BookStarterTests_ShellCollection");
			_libraryFolder = new TemporaryFolder("BookStarterTests_LibraryCollection");
		}
コード例 #19
0
 private static IRulesProvider MakeMockRuleProvider(Type forModelType, params string[] rulePropertyNames)
 {
     var ruleset = new RuleSet(rulePropertyNames.ToLookup(x => x, x => (Rule)new RequiredRule()));
     var mockProvider = new Moq.Mock<IRulesProvider>();
     mockProvider.Expect(x => x.GetRulesFromType(forModelType)).Returns(ruleset);
     return mockProvider.Object;
 }
コード例 #20
0
        void Setup_the_SUT()
        {
            DomainEventPublisherMock = new Moq.Mock<IPublishDomainEvents>(Moq.MockBehavior.Loose);

            State = new ProductState(DomainEventPublisherMock.Object);

            SUT = new Product(State);
        }
コード例 #21
0
        public void SetBuildValidationServiceSomethingElseTest()
        {
            Moq.Mock<IValidationService> mockService = new Moq.Mock<IValidationService>();

            Factories.BuildValidationService = () => mockService.Object;
            var actual = Factories.BuildValidationService();
            Assert.AreEqual(mockService.Object, actual);
        }
コード例 #22
0
 public void SetUp()
 {
     List<Product> allProducts = new List<Product>();
     for (int i = 1; i <= 50; i++)
         allProducts.Add(new Product { ProductID = i, Name = "Product " + i });
     mockRepository = new Moq.Mock<IProductsRepository>();
     mockRepository.Setup(x => x.Products).Returns(allProducts.AsQueryable);
 }
コード例 #23
0
 public void MyTestInitialize()
 {
     mockIntel = new Moq.Mock<IIntelService>();
     mockPeer = new Moq.Mock<IPeerRegistration>();
     mockServiceHost = new Moq.Mock<IServiceHost>();
     mockServiceHost.Setup(mock => mock.PeerRegistration).Returns(mockPeer.Object);
     target = new ServicePresenter(mockIntel.Object,  mockServiceHost.Object);
 }
コード例 #24
0
 public void ReturnsEmptySummaryIfInputIsNullOrEmpty()
 {
     var mocValidator = new Moq.Mock<IInputValidator>();
     mocValidator.Setup(val => val.IsValidInput(new List<string>(), null)).Returns(true);
     var abnfFileProcess = new AbnfContentProcessor(mocValidator.Object);
     var flightSummary = abnfFileProcess.Process(null);
     Assert.IsNotNull(flightSummary);
 }
コード例 #25
0
ファイル: UserTest.cs プロジェクト: hlim29/ENET_Care_A1
 public void Login_AdminPassword_True()
 {
     var dummyUser = new Moq.Mock<User>();
     dummyUser.SetupProperty(user => user.Email, "*****@*****.**")
                 .SetupProperty(user => user.Password, "password");
     User userObject = dummyUser.Object;
     Assert.AreNotEqual(null, userObject.login("*****@*****.**", "password"));
 }
コード例 #26
0
 private ControllerContext GenerateControllerContext(ControllerBase controller)
 {
     var fakeIdentity = new GenericIdentity("Jimmy");
     var fakeUser = new GenericPrincipal(fakeIdentity,null);
     var httpContext = new Moq.Mock<HttpContextBase>();
     httpContext.Setup(x => x.User).Returns(fakeUser);
     var reqContext = new RequestContext(httpContext.Object, new RouteData());
     return new ControllerContext(reqContext, controller);
 }
コード例 #27
0
ファイル: GeneratedClientTest.cs プロジェクト: nerdrew/grpc
        public void CallOptionsOverloadCanBeMocked()
        {
            var expected = new SimpleResponse();

            var mockClient = new Moq.Mock<TestService.TestServiceClient>();
            mockClient.Setup(m => m.UnaryCall(Moq.It.IsAny<SimpleRequest>(), Moq.It.IsAny<CallOptions>())).Returns(expected);

            Assert.AreSame(expected, mockClient.Object.UnaryCall(new SimpleRequest(), new CallOptions()));
        }
コード例 #28
0
 public void Setup()
 {
     m_MockCategoryControl = new Moq.Mock<ICategoryControl>();
     m_MockCategoryControl.SetupAllProperties();
     m_MockSerieControl = new Moq.Mock<ISerieControl>();
     m_MockSerieControl.SetupAllProperties();
     m_MockFigurControl = new Moq.Mock<IFigurControl>();
     m_MockFigurControl.SetupAllProperties();
 }
コード例 #29
0
 public void SetUp()
 {
     mockOrdinalSuffixProvider = new Moq.Mock<OrdinalSuffixProvider>();
     mockGenerator = new Moq.Mock<RandomNumberGenerator>(null, null, null);
     mockGuessService = new Moq.Mock<GuessService>(null);
     controller = new HomeController(mockGenerator.Object, mockOrdinalSuffixProvider.Object, mockGuessService.Object);
     mockControllerContext = new Moq.Mock<ControllerContext>();
     controller.ControllerContext = mockControllerContext.Object;
 }
コード例 #30
0
ファイル: EventBusTests.cs プロジェクト: jchristian/net_worth
        public void should_execute_the_handler_when_an_event_is_raised()
        {
            var handler = new Moq.Mock<CreateLotsForBrokerageTransactions>();
            var @event = new BrokerageTransactionsPersisted(null);

            new EventBus(handler.Object).Raise(@event);

            handler.Verify(x => x.Handle(@event));
        }
コード例 #31
0
        public async System.Threading.Tasks.Task JobTestAsync()
        {
            var repository = LogManager.CreateRepository(Common.LogFactory.repositoryName);

            // 指定配置文件
            XmlConfigurator.Configure(repository, new FileInfo("log4net.config"));
            var logger    = new Moq.Mock <ILogger <DataAccess> >();
            var sp        = new Moq.Mock <IServiceProvider>();
            var myContext = new Service.Context.XinDBContext(new Microsoft.EntityFrameworkCore.DbContextOptions <Service.Context.XinDBContext>());

            sp.Setup((o) => o.GetService(typeof(IEntityContext))).Returns(myContext);

            sp.Setup((o) => o.GetService(typeof(IRepository <ECTransitBatchNumber>)))
            .Returns(new GenericEntityRepository <ECTransitBatchNumber>(logger.Object));
            var provider = new UowProvider(logger.Object, sp.Object);
            EcTransitBatchNumberInit job = new EcTransitBatchNumberInit(provider);
            await job.Job();
        }
コード例 #32
0
        public void Setup()
        {
            _metrics    = new Moq.Mock <IMetrics>();
            _consumer   = new Moq.Mock <IEventStoreConsumer>();
            _dispatcher = new Moq.Mock <IMessageDispatcher>();

            var fake = new FakeConfiguration();

            fake.FakeContainer.Setup(x => x.Resolve <IMetrics>()).Returns(_metrics.Object);
            fake.FakeContainer.Setup(x => x.Resolve <IEventStoreConsumer>()).Returns(_consumer.Object);
            fake.FakeContainer.Setup(x => x.Resolve <IMessageDispatcher>()).Returns(_dispatcher.Object);

            Configuration.Settings = fake;

            _dispatcher.Setup(x => x.SendLocal(Moq.It.IsAny <IFullMessage[]>(), Moq.It.IsAny <IDictionary <string, string> >())).Returns(Task.CompletedTask);

            _subscriber = new Aggregates.Internal.DelayedSubscriber(_metrics.Object, _consumer.Object, _dispatcher.Object, 1);
        }
コード例 #33
0
        public void Wiring_OffProviderNotAssigned()
        {
            //arrange
            var light         = new Moq.Mock <MyLight>(new NullLogger <MyLight>());
            var switchOptions = new SwitcherProviderOptions();
            var switcher      = new Switcher(new NullLogger <Switcher>(), switchOptions);
            var dateTime      = new Moq.Mock <IDateTimeProvider>();
            var timed         = new Moq.Mock <TimedSwitcherProvider>(dateTime.Object);
            var x             = new MyTimerLightWiring(light.Object, switcher, timed.Object);

            //act

            //assert
            Action expected = light.Object.Off;
            Action actual   = x.Switcher.SwitchingProvider.SwitchOffProvider;

            Assert.NotEqual(expected, actual);
        }
コード例 #34
0
        public void ShouldFailWhenMetricsNotInstalled()
        {
            if (this.MetricsInstalled)
            {
                Assert.IsTrue(true);
                return;
            }

            var mock = new Moq.Mock <IMetricsLogger>();

            // Create a WorkflowInvoker and add the IBuildDetail Extension
            var target = MetricsInvoker.Create(new List <string> {
                "*.dll"
            }, @"c:\binaries", "Metrics.exe", mock.Object);

            Assert.IsNull(target);
            mock.Verify(m => m.LogError(Moq.It.Is <string>(s => s.Contains("Could not locate"))));
        }
コード例 #35
0
        public void ShouldNotFailWhenMetricsIsInstalled()
        {
            if (!this.MetricsInstalled)
            {
                Assert.IsTrue(true);
                return;
            }

            var mock = new Moq.Mock <IMetricsLogger>();

            // Create a WorkflowInvoker and add the IBuildDetail Extension
            var target = MetricsInvoker.Create(new List <string> {
                "*.dll"
            }, @"c:\binaries", "Metrics.exe", mock.Object);

            Assert.IsNotNull(target);
            mock.Verify(m => m.LogError(Moq.It.IsAny <string>()), Moq.Times.Never());
        }
コード例 #36
0
        public void When_Greeted_During_Night_GreetNightView_Is_Returned()
        {
            //Arrange
            var mockFactory = new Moq.Mock <ITimeService>();

            mockFactory.Setup(ts => ts.GetCurrentTime()).Returns(new DateTime(2013, 9, 6, 21, 0, 0));
            var timeService   = mockFactory.Object;
            var testFirstName = "Magesh";
            var testLastName  = "K";
            var controller    = new GreetingController(timeService);

            //Act
            var result = controller.Greet(testFirstName, testLastName);

            //Assert
            Assert.AreEqual("GreetNightView", result.ViewName);
            Assert.AreEqual("Good Night " + testLastName + ", " + testFirstName, result.ViewData["greetMsg"]);
        }
コード例 #37
0
        public async Task is_event_with_mutators()
        {
            var context  = new Moq.Mock <IOutgoingLogicalMessageContext>();
            var next     = new Moq.Mock <Func <Task> >();
            var mutator  = new Moq.Mock <IEventMutator>();
            var mutating = new Moq.Mock <IMutating>();

            mutating.Setup(x => x.Headers).Returns(new Dictionary <string, string>());
            mutator.Setup(x => x.MutateOutgoing(Moq.It.IsAny <IMutating>())).Returns(mutating.Object);
            context.Setup(x => x.Builder.BuildAll <IEventMutator>()).Returns(new IEventMutator[] { mutator.Object });
            context.Setup(x => x.Message).Returns(new OutgoingLogicalMessage(typeof(Event), new Event()));

            await _mutator.Invoke(context.Object, next.Object);

            next.Verify(x => x(), Moq.Times.Once);
            mutator.Verify(x => x.MutateOutgoing(Moq.It.IsAny <IMutating>()), Moq.Times.Once);
            context.Verify(x => x.UpdateMessage(Moq.It.IsAny <object>()), Moq.Times.Once);
        }
コード例 #38
0
        public void Greets_With_GoodMorning_Before_12()
        {
            //Arrange
            var mockery = new Moq.Mock <ITimeService>();

            mockery.Setup(ts => ts.GetCurrentTime()).Returns(new DateTime(2015, 1, 27, 9, 0, 0));
            var timeService = mockery.Object;
            var greeter     = new Greeter(timeService);

            var    name           = "Magesh";
            string expectedResult = "Hi Magesh, Good Morning";
            //Act
            var greetMsg = greeter.Greet(name);

            //Assert

            Assert.AreEqual(expectedResult, greetMsg);
        }
コード例 #39
0
        public async Task write_events_not_frozen()
        {
            _store.Setup(x => x.IsFrozen(Moq.It.IsAny <string>())).Returns(Task.FromResult(false));
            _store.Setup(x => x.WriteEvents(Moq.It.IsAny <string>(), Moq.It.IsAny <IEnumerable <IFullEvent> >(),
                                            Moq.It.IsAny <IDictionary <string, string> >(), Moq.It.IsAny <long>())).Returns(Task.FromResult(0L));

            var @event = new Moq.Mock <IFullEvent>();

            @event.Setup(x => x.Descriptor.StreamType).Returns(StreamTypes.Domain);
            @event.Setup(x => x.Descriptor.Headers).Returns(new Dictionary <string, string>());

            _stream.Setup(x => x.Uncommitted).Returns(new IFullEvent[] { @event.Object }.AsEnumerable());

            await _streamStore.WriteStream <Entity>(Guid.NewGuid(), _stream.Object, new Dictionary <string, string>());

            _store.Verify(x => x.WriteEvents(Moq.It.IsAny <string>(), Moq.It.IsAny <IEnumerable <IFullEvent> >(),
                                             Moq.It.IsAny <IDictionary <string, string> >(), Moq.It.IsAny <long>()), Moq.Times.Once);
        }
コード例 #40
0
        public void When_Greeted_After_12_Returns_GoodAfternoon()
        {
            //Arrange
            var mockery = new Moq.Mock <IDateTimeService>();

            mockery.Setup(s => s.GetCurrent()).Returns(new DateTime(2016, 1, 10, 15, 0, 0));
            var mockDateTimeService = mockery.Object;

            var greeterService  = new GreeterService(mockDateTimeService);
            var name            = "Magesh";
            var expectedMessage = "Hi Magesh, Good Afternoon!";

            //Act
            var greetMessage = greeterService.Greet(name);

            //Assert
            Assert.AreEqual(expectedMessage, greetMessage);
        }
コード例 #41
0
        public void Setup()
        {
            _uow        = new Moq.Mock <IDomainUnitOfWork>();
            _factory    = new Moq.Mock <IEventFactory>();
            _eventstore = new Moq.Mock <IStoreEvents>();
            _oobWriter  = new Moq.Mock <IOobWriter>();
            _mapper     = new Moq.Mock <IEventMapper>();

            _mapper.Setup(x => x.GetMappedTypeFor(typeof(Test))).Returns(typeof(Test));
            var fake = new FakeConfiguration();

            fake.FakeContainer.Setup(x => x.Resolve <IEventMapper>()).Returns(_mapper.Object);
            Configuration.Settings = fake;

            _entity = new FakeEntity(_factory.Object, _eventstore.Object, _oobWriter.Object);
            (_entity as IEntity <FakeState>).Instantiate(new FakeState());
            (_entity as INeedDomainUow).Uow = _uow.Object;
        }
コード例 #42
0
        public void Given_Invalid_ReportFilePath_When_WriteReportsToCSV_Invoked_Then_False_Asserted()
        {
            Directory.SetCurrentDirectory(@"C:\Users\320052125\casestudy2\Analyser");
            StaticCodeAnalysisReportsCSVMerger obj = new StaticCodeAnalysisReportsCSVMerger();

            string[] a1 = new string[] { };
            string[] a2 = new string[] { };

            Moq.Mock <IStaticCodeAnalysisToolParser> _mockWrapper = new Moq.Mock <IStaticCodeAnalysisToolParser>();
            _mockWrapper.Setup(x => x.ParseReportToCSV(a1)).Returns(a2);

            string reportFilePath = @"notexists";
            string outfileFath    = @"FinalReport.csv";

            bool actualValue = obj.WriteReportsToCSV(_mockWrapper.Object, reportFilePath, outfileFath);

            Assert.AreEqual(false, actualValue);
        }
コード例 #43
0
        public void GetBeersReturnResult()
        {
            var mockRequestModel = new Request();

            var mockBeersModel = new Beers();

            var mockBeerProvide = new Moq.Mock <IBeerProvider>();

            mockBeerProvide.Setup(x => x.GetBeers(mockRequestModel)).Returns(mockBeersModel);
            var controller = new BeerController(mockBeerProvide.Object);

            //Act
            IHttpActionResult actionResult = controller.GetBeers(mockRequestModel);

            //Assert
            Assert.IsNotNull(actionResult);
            Assert.IsInstanceOfType(actionResult, typeof(OkNegotiatedContentResult <Beers>));
        }
コード例 #44
0
        public async Task PostOneEHObj_ShouldSucceed_UnitTest()
        {
            var mock = new Moq.Mock <IWebObjectService>();

            mock.Setup(m => m.AddEmployeeHours(Moq.It.IsAny <WebEmployeeHours>()));
            using (var testServer = new TestServerBuilder()
                                    .WithMock <IWebObjectService>(typeof(IWebObjectService), mock)
                                    .Build())
            {
                var         client         = testServer.CreateClient();
                var         myJson         = "{ 'employeeId': 33 }";
                HttpContent requestContent = new StringContent(myJson, Encoding.UTF8, "application/json");
                var         response       = await client.PostAsync("/api/employee_hours", requestContent);

                Assert.Equal(System.Net.HttpStatusCode.Created, response.StatusCode);
            }
            mock.Verify(m => m.AddEmployeeHours(Moq.It.IsAny <WebEmployeeHours>()), Moq.Times.Once);
        }
コード例 #45
0
        public void Login(string email, string password)
        {
            agency = new PPCRental_Project.Controllers.AccountController();
            db     = new K21T3_Team1_PPC3129Entities();
            us     = db.USER.FirstOrDefault(d => d.Email == email);

            var moqContext = new Moq.Mock <ControllerContext>();
            var moqSession = new Moq.Mock <HttpSessionStateBase>();

            moqContext.Setup(c => c.HttpContext.Session).Returns(moqSession.Object);
            agency.ControllerContext = moqContext.Object;
            moqSession.Setup(s => s["UserRole"]).Returns("1");

            us.Email    = email;
            us.Password = password;

            agency.Login(email, password);
        }
コード例 #46
0
        public void Can_use_Dsl_to_send_an_email()
        {
            // arrange
            // redirect the console
            var consoleOut = Helpers.Logging.RedirectConsoleOut();

            var emailProvider       = new Moq.Mock <IEmailProvider>();
            var azureDevOpsProvider = new Moq.Mock <IAzureDevOpsProvider>();
            var eventDataProvider   = new Moq.Mock <IEventDataProvider>();

            var engine = new AzureDevOpsEventsProcessor.Dsl.DslProcessor();

            // act
            engine.RunScript(@"TestDataFiles\Scripts\email\sendemail.py", azureDevOpsProvider.Object, emailProvider.Object, eventDataProvider.Object);

            // assert
            emailProvider.Verify(e => e.SendEmailAlert("*****@*****.**", "The subject", "The body of the email"));
        }
コード例 #47
0
ファイル: UnitTest1.cs プロジェクト: haitongxuan/Xin2
        public void TestOne2many()
        {
            var logger    = new Moq.Mock <ILogger <DataAccess> >();
            var sp        = new Moq.Mock <IServiceProvider>();
            var myContext = new Service.Context.XinDBContext(new Microsoft.EntityFrameworkCore.DbContextOptions <Service.Context.XinDBContext>());

            sp.Setup((o) => o.GetService(typeof(IEntityContext))).Returns(myContext);

            sp.Setup((o) => o.GetService(typeof(IRepository <ResUser>)))
            .Returns(new GenericEntityRepository <ResUser>(logger.Object));
            var provider = new UowProvider(logger.Object, sp.Object);

            using (var uow = provider.CreateUnitOfWork())
            {
                var repository = uow.GetRepository <ResUser>();
                var user       = repository.Query(x => x.UserName == "admin" && x.UserPwd == SecretHelper.MD5Encrypt("h111111", "h111111"));
            }
        }
コード例 #48
0
        public void current_memento()
        {
            var memento = new Moq.Mock <IMemento>();

            memento.Setup(x => x.EntityId).Returns("test");

            var snapshot = new Moq.Mock <ISnapshot>();

            snapshot.Setup(x => x.Version).Returns(1);
            snapshot.Setup(x => x.Payload).Returns(memento.Object);

            // _events contains 1 event
            var stream = new Aggregates.Internal.EventStream <Entity>("test", "test", null, null, _events, snapshot.Object);

            Assert.AreEqual(1, stream.StreamVersion);

            Assert.AreEqual(new Id("test"), stream.Snapshot.Payload.EntityId);
        }
コード例 #49
0
        public void Error_logged_if_no_Dsl_library_folder_found()
        {
            // arrange
            var emailProvider = new Moq.Mock <IEmailProvider>();
            var tfsProvider   = new Moq.Mock <ITfsProvider>();

            // create a memory logger
            var memLogger = Helpers.Logging.CreateMemoryTargetLogger(LogLevel.Info);
            var engine    = new TFSEventsProcessor.Dsl.DslProcessor();

            // act
            engine.RunScript(@"c:\dummy", @"dsl\scripting\args.py", string.Empty, null, tfsProvider.Object, emailProvider.Object, string.Empty);

            // assert
            Assert.AreEqual(2, memLogger.Logs.Count);
            // memLogger.Logs[0] is the log message from the runscript method
            Assert.AreEqual(@"ERROR | TFSEventsProcessor.Dsl.DslProcessor | TFSEventsProcessor: DslProcessor cannot find DSL folder c:\dummy", memLogger.Logs[1]);
        }
コード例 #50
0
ファイル: DelayedCache.cs プロジェクト: virajs/Aggregates.NET
        public async Task add_and_pull()
        {
            _cache = new Internal.DelayedCache(_metrics.Object, _store.Object, TimeSpan.FromSeconds(1), "test", int.MaxValue, int.MaxValue, TimeSpan.MaxValue, (a, b, c, d, e) => "test");

            var msg = new Moq.Mock <IDelayedMessage>();

            msg.Setup(x => x.MessageId).Returns("test");
            await _cache.Add("test", "test", new[] { msg.Object });

            var size = await _cache.Size("test", "test");

            Assert.AreEqual(1, size);

            var result = await _cache.Pull("test", "test");

            Assert.AreEqual(1, result.Length);
            Assert.AreEqual("test", result[0].MessageId);
        }
コード例 #51
0
        public void SearchBeersReturnResult(string queryRequest)
        {
            var mockRequestModel = new Request {
                query = queryRequest
            };

            var mockBeersModel = new Beers();

            var mockContextProvide = new Moq.Mock <IContextProvider>();

            mockContextProvide.Setup(x => x.GetBeersAsync($"&q={queryRequest}&type=beer", "search/")).Returns(mockBeersModel);
            var provider = new BeerProvider(mockContextProvide.Object);

            Beers beers = provider.SearchBeers(mockRequestModel);

            Assert.IsNotNull(beers);
            Assert.IsTrue(beers.data.Count > 0, "beera.data should be greater than 0");
        }
コード例 #52
0
        public void ValidHttpResponse()
        {
            Moq.Mock <HttpWebResponse> fakeResponse = new Moq.Mock <HttpWebResponse>();
            fakeResponse.Setup(response => response.StatusCode).Returns(HttpStatusCode.OK);
            Moq.Mock <HttpWebRequest> fakeRequest = new Moq.Mock <HttpWebRequest>();
            fakeRequest.Setup(request => request.GetResponse()).Returns(fakeResponse.Object);

            bo.Web.WebPageContent content = new bo.Web.WebPageContent();

            content.request = fakeRequest.Object;
            Assert.IsTrue(content.TryGetResponse());

            content = new bo.Web.WebPageContent();
            //content.SetRequestFromURL("http://www.tyre-shopper.co.uk/robots.txt
            content.SetRequestFromURL("http://localhost:4174/");

            Assert.IsTrue(content.TryGetResponse());
        }
コード例 #53
0
        public void AddInterceptor_BeforeAnAlreadyAddedInterceptor_ReturnsInterceptorsInExpectedOrder()
        {
            // arrange
            var serviceCollection   = new Moq.Mock <IServiceCollection>();
            var bootstrapperOptions = new BootstrapperOptions(serviceCollection.Object);

            // act
            bootstrapperOptions.AddInterceptor <TransactionInterceptor>().Before <StopwatchInterceptor>();

            // assert
            var interceptorTypes            = bootstrapperOptions.InterceptorTypes.ToList();
            var stopWatchInterceptorIndex   = interceptorTypes.IndexOf(typeof(StopwatchInterceptor));
            var transactionInterceptorIndex = interceptorTypes.IndexOf(typeof(TransactionInterceptor));

            Assert.True(stopWatchInterceptorIndex != -1);
            Assert.True(transactionInterceptorIndex != -1);
            Assert.True(transactionInterceptorIndex < stopWatchInterceptorIndex);
        }
コード例 #54
0
        public void SetUp()
        {
            controller = new ArtistController(null, null, null);

            var responseMock = new Moq.Mock <HttpResponseBase>();

            responseMock.SetupProperty(m => m.StatusCode);
            responseMock.SetupProperty(m => m.StatusDescription);
            response = responseMock.Object;

            var context = new Moq.Mock <HttpContextBase>();

            context.SetupGet(m => m.Response).Returns(response);
            var controllerContext = new Moq.Mock <ControllerContext>();

            controllerContext.SetupGet(m => m.HttpContext).Returns(context.Object);
            controller.ControllerContext = controllerContext.Object;
        }
コード例 #55
0
        public void ThrowsValidationExceptionIfDgpHeaderRequiredAndMissing()
        {
            //Arrange
            var loggerMock         = new Moq.Mock <ILogger <CorrelationMiddleware> >();
            var applicationContext = new Moq.Mock <IApplicationContext>();
            var middleware         = new CorrelationMiddleware(next: async(innerHttpContext) => { await innerHttpContext.Response.WriteAsync("test response body"); }, logger: loggerMock.Object, applicationContext: applicationContext.Object);
            var options            = Options.Create <CorrelationOptions>(new CorrelationOptions()
            {
                CorrelationHeaderRequired = true
            });
            var correlationContext = new CorrelationContext(options);
            var httpContext        = new DefaultHttpContext();

            httpContext.RequestServices = new Moq.Mock <IServiceProvider>().Object;

            //Act
            Assert.ThrowsAsync <ValidationException>(() => middleware.Invoke(httpContext, options));
        }
コード例 #56
0
        public void AddInterceptor_AfterAlreadyAddedInterceptor_ReturnsInterceptorsInExpectedOrder()
        {
            // arrange
            var serviceCollection = new Moq.Mock <IServiceCollection>();
            var boltOnOptions     = new BoltOnOptions(serviceCollection.Object);

            // act
            boltOnOptions.AddInterceptor <StopwatchInterceptor>().After <UnitOfWorkInterceptor>();

            // assert
            var interceptorTypes          = boltOnOptions.InterceptorTypes.ToList();
            var stopWatchInterceptorIndex = interceptorTypes.IndexOf(typeof(StopwatchInterceptor));
            var uowInterceptorIndex       = interceptorTypes.IndexOf(typeof(UnitOfWorkInterceptor));

            Assert.True(stopWatchInterceptorIndex != -1);
            Assert.True(uowInterceptorIndex != -1);
            Assert.True(uowInterceptorIndex < stopWatchInterceptorIndex);
        }
コード例 #57
0
            public void MixedImageReturnsMixedPalette()
            {
                var image = new Moq.Mock <IImage>();

                image.Setup(x => x.Width).Returns(1);
                image.Setup(x => x.Height).Returns(2);
                image.Setup(x => x.GetPixel(0, 0)).Returns(Color.Red);
                image.Setup(x => x.GetPixel(0, 1)).Returns(Color.Blue);

                var p = new PercentagePaletteInventory
                {
                    Image = image.Object
                };

                // TODO: 2 Asserts, smells bad
                Assert.IsTrue(Math.Abs(p.Items[Color.Red] - .5) < Epsilon);
                Assert.IsTrue(Math.Abs(p.Items[Color.Blue] - .5) < Epsilon);
            }
コード例 #58
0
        public void Setup()
        {
            _builder      = new Moq.Mock <IBuilder>();
            _eventStore   = new Moq.Mock <IStoreEvents>();
            _eventStream  = new Moq.Mock <IEventStream>();
            _eventRouter  = new Moq.Mock <IEventRouter>();
            _eventFactory = new Moq.Mock <IMessageCreator>();
            _eventStream.Setup(x => x.Commit(Moq.It.IsAny <Guid>(), Moq.It.IsAny <IDictionary <String, String> >())).Verifiable();
            _eventStream.Setup(x => x.ClearChanges()).Verifiable();
            _eventStore.Setup(x => x.GetStream <_AggregateStub>(Moq.It.IsAny <String>(), Moq.It.IsAny <String>(), Moq.It.IsAny <Int32?>())).Returns(_eventStream.Object);
            _aggregate = new Moq.Mock <_AggregateStub>();
            _builder.Setup(x => x.CreateChildBuilder()).Returns(_builder.Object);
            _builder.Setup(x => x.Build <IEventRouter>()).Returns(_eventRouter.Object);
            _builder.Setup(x => x.Build <IMessageCreator>()).Returns(_eventFactory.Object);
            _builder.Setup(x => x.Build <IStoreEvents>()).Returns(_eventStore.Object);

            _repository = new Aggregates.Internal.Repository <_AggregateStub>(_builder.Object);
        }
コード例 #59
0
        public void Setup()
        {
            _builder        = new Moq.Mock <IBuilder>();
            _eventStore     = new Moq.Mock <IStoreEvents>();
            _bus            = new Moq.Mock <IBus>();
            _guidRepository = new Moq.Mock <IRepository <_AggregateStub <Guid> > >();
            _repoFactory    = new Moq.Mock <IRepositoryFactory>();
            _processor      = new Moq.Mock <IProcessor>();
            _mapper         = new Moq.Mock <IMessageMapper>();

            _builder.Setup(x => x.Build <IRepository <_AggregateStub <Guid> > >()).Returns(_guidRepository.Object);
            _builder.Setup(x => x.CreateChildBuilder()).Returns(_builder.Object);
            _builder.Setup(x => x.Build <IProcessor>()).Returns(_processor.Object);
            _repoFactory.Setup(x => x.ForAggregate <_AggregateStub <Guid> >(Moq.It.IsAny <IBuilder>())).Returns(_guidRepository.Object);

            _uow         = new Aggregates.Internal.UnitOfWork(_repoFactory.Object, _mapper.Object);
            _uow.Builder = _builder.Object;
        }
コード例 #60
0
        private ICartBuilder GetCartBuilder()
        {
            var apiClientCfg         = new Client.Client.Configuration(GetApiClient());
            var marketingApi         = new MarketingModuleApi(apiClientCfg);
            var cartApi              = new ShoppingCartModuleApi(apiClientCfg);
            var cacheManager         = new Moq.Mock <ICacheManager <object> >();
            var workContextFactory   = new Func <WorkContext>(GetTestWorkContext);
            var promotionEvaluator   = new PromotionEvaluator(marketingApi);
            var catalogModuleApi     = new CatalogModuleApi(apiClientCfg);
            var pricingApi           = new PricingModuleApi(apiClientCfg);
            var pricingService       = new PricingServiceImpl(workContextFactory, pricingApi);
            var inventoryApi         = new InventoryModuleApi(apiClientCfg);
            var searchApi            = new SearchModuleApi(apiClientCfg);
            var catalogSearchService = new CatalogSearchServiceImpl(workContextFactory, catalogModuleApi, pricingService, inventoryApi, searchApi, promotionEvaluator);
            var retVal = new CartBuilder(cartApi, promotionEvaluator, catalogSearchService, cacheManager.Object);

            return(retVal);
        }