public void ShouldReturnCorrectProductFromProductsRepository(int id, string expectedProductName)
        {
            // Arrange
            var mockedProducts = new List <Product>
            {
                new Product()
                {
                    Id = 2, Name = "Second product"
                },
                new Product()
                {
                    Id = 4, Name = "Forth product"
                }
            };
            var mockedUnitOfWork        = new Mock <IUnitOfWork>();
            var mockedGenericRepository = new Mock <IGenericRepository <Product> >();

            mockedGenericRepository.Setup(gr => gr.GetById(id))
            .Returns(mockedProducts.Find(p => p.Id == id));

            var productsService = new ProductsService(mockedUnitOfWork.Object, mockedGenericRepository.Object);

            // Act
            var result = productsService.GetProductById(id);

            // Assert
            Assert.AreEqual(expectedProductName, result.Name);
        }
示例#2
0
        public IActionResult <IEnumerable <ProductViewModel> > Products(string productName)
        {
            var productService = new ProductsService(Data.Data.Context);
            var viewModels     = productService.GetProducts(productName);

            return(View(viewModels));
        }
        // GET: Home
        public ActionResult AdminHome()
        {
            if ((bool?)Session["AdminLogin"] == null)
            {
                return(RedirectToAction("AdminHomeLogin"));
            }

            var serviceCus = new CustomerService();
            var serviceOd  = new OrderDetailsService();
            var serviceOr  = new OrderService();
            var servicePro = new ProductsService();

            ViewBag.CostomerNumber = serviceCus.GetAll().Count();
            ViewBag.OrderNumber    = serviceOr.GetAll().Count();
            var ProductNumber = serviceOd.GetAll();
            var Number        = 0;

            foreach (var item in ProductNumber)
            {
                Number += item.Quantity;
            }
            ViewBag.ProductNumber = Number;
            var     GetAllOrder = serviceOd.GetAll();
            decimal total       = 0;

            foreach (var item in GetAllOrder)
            {
                total += servicePro.FindByID(item.ProductID).UnitPrice *item.Quantity;
            }
            ViewBag.Total = Decimal.Round(total);

            return(View());
        }
示例#4
0
        public async Task CreateAsyncShouldCreateProduct()
        {
            var dbContext       = ApplicationDbContextInMemoryFactory.InitializeContext();
            var repository      = new EfDeletableEntityRepository <Product>(dbContext);
            var productsService = new ProductsService(repository);

            var product = new Product()
            {
                Name        = "TestProduct",
                Description = "none",
                CategoryId  = 3,
                Category    = new Category()
                {
                    Id = 3, Name = "Test Category "
                },
                ImageUrl         = null,
                ImageStorageName = null,
                Sizes            = new List <ProductSize>()
                {
                    new ProductSize()
                    {
                        Id = 1, Name = "S", Price = 5M
                    }
                },
                Ratings = null,
            };

            await productsService.CreateAsync(product);

            var products      = dbContext.Products.ToList();
            var productsCount = products.Count;

            Assert.Equal(1, productsCount);
        }
        public ActionResult SimpleProduct(int id)
        {
            var products_service = new ProductsService();
            //var discounts_service = new DiscountsService();  目前沒折扣資料 先不抓
            var size_service       = new SizeService();
            var stockcolor_service = new StockColorService();
            //var image_service = new ImageService();  沒照片 不抓

            var list = new List <SizeStockCombineViewModel>();

            foreach (var i in products_service.GetProductsTable())
            {
                if (id == i.ProductID)
                {
                    ViewBag.ProductName = i.ProductName;

                    ViewBag.ProductID = i.ProductID;
                    ViewBag.UnitPrice = i.UnitPrice;
                    break;
                }
            }

            var size       = size_service.GetSizeTable().Where(x => x.ProductID == id).ToList();
            var stockcolor = stockcolor_service.GetStockColorsTable(id).ToList();

            list.Add(new SizeStockCombineViewModel()
            {
                Size       = size,
                StockColor = stockcolor
            });

            return(View(list));
        }
示例#6
0
        public ActionResult GetProducts(int page, List <Product> AllProducts)
        {
            //每八個一頁
            var ProductNumber = 8;
            //取得目前頁所需要顯示的物品
            var pList = AllProducts.Skip((page - 1) * ProductNumber).Take(ProductNumber).ToList();

            //建立全部商品
            ProductsService service           = new ProductsService(db);
            var             AllProductDetails = service.getPageOfProducts();
            var             Model             = new List <ProductPageViewModel>();

            for (var i = 0; i < pList.Count; i++)
            {
                //避免超出範圍,雖然不一定會用到
                if (i % 8 == 0 && i != 0)
                {
                    break;
                }

                //取得此產品ID所有的PDID,並加進List<ProductPageViewModel> Model中
                var FilterList = AllProductDetails.Where(x => x.ProductID == pList[i].ProductID);
                foreach (var item in FilterList)
                {
                    Model.Add(item);
                }
            }
            ViewData.Model = Model;
            return(PartialView("_ProductsPartial"));
        }
        public async Task CheckFavouriteProductFalseCaseAsync()
        {
            ApplicationDbContext db = GetDb();

            var repository = new EfDeletableEntityRepository <Product>(db);
            var clientProductLikesRepository = new EfRepository <ClientProductLike>(db);

            var service = new ProductsService(
                repository,
                clientProductLikesRepository,
                this.cloudinaryService.Object);

            var product = new Product()
            {
                Id   = "1",
                Name = "firstProductName",
            };

            var client = new ApplicationUser()
            {
                Id = "1",
            };

            await db.Products.AddAsync(product);

            await db.Users.AddAsync(client);

            await db.SaveChangesAsync();

            var isFavourite = await service.CheckFavouriteProductsAsync(product.Id, client.Id);

            Assert.True(!isFavourite);
        }
        public async Task Return_True_IfItExists()
        {
            //Arrange
            var options = new DbContextOptionsBuilder <GameStoreContext>()
                          .UseInMemoryDatabase("Return_True_IfItExists").Options;

            var product = new Product
            {
                Name                 = "Test",
                Description          = "test description",
                ShoppingCartProducts = new List <ShoppingCartProducts>(),
                Comments             = new List <Comment>()
            };

            //Act
            using (var curContext = new GameStoreContext(options))
            {
                curContext.Products.Add(product);
                curContext.SaveChanges();
                var sut    = new ProductsService(curContext);
                var result = await sut.ProductExistsAsync(product.Id);

                Assert.IsTrue(result);
            }
        }
示例#9
0
        public async Task TotalCost_MultipleItemsSingleTimes()
        {
            var prodRepo        = new MockRepository <Product>();
            var basketRepo      = new MockRepository <ProductInBasket>();
            var productsService = new ProductsService(prodRepo);
            var basketService   = new BasketService(basketRepo, productsService);

            productsService.Add(new Product
            {
                Id    = 1,
                Price = 10.0M
            });

            productsService.Add(new Product
            {
                Id    = 2,
                Price = 99.0M
            });

            productsService.Add(new Product
            {
                Id    = 3,
                Price = 5.5M
            });

            var userId = "UserA";

            basketService.Add(new ProductInBasket {
                Id = 1, ProductId = 1, UserId = userId, Count = 20
            });

            Assert.True(basketService.TotalCost(userId) == 200.0M);
        }
        public void EditProductProductShouldEditProduct()
        {
            var options = new DbContextOptionsBuilder <XeonDbContext>()
                          .UseInMemoryDatabase(databaseName: "Add_Product_Database")
                          .Options;

            var dbContext      = new XeonDbContext(options);
            var productService = new ProductsService(dbContext);

            var product = new Product
            {
                Name          = "USB",
                ParnersPrice  = 31,
                Price         = 39,
                Specification = "1.1"
            };

            dbContext.Products.Add(product);
            dbContext.SaveChanges();

            product.Name          = "NewName";
            product.ParnersPrice  = 11;
            product.Price         = 10;
            product.Specification = "2.0";
            productService.EditProduct(product);

            var editedProduct = dbContext.Products.FirstOrDefault(x => x.Name == product.Name);

            Assert.Equal(product.Name, editedProduct.Name);
            Assert.Equal(product.ParnersPrice, editedProduct.ParnersPrice);
            Assert.Equal(product.Price, editedProduct.Price);
            Assert.Equal(product.Specification, editedProduct.Specification);
        }
        public void HideProductShouldChangeHiteToTrue()
        {
            var options = new DbContextOptionsBuilder <XeonDbContext>()
                          .UseInMemoryDatabase(databaseName: "Remove_Product_Database")
                          .Options;

            var dbContext      = new XeonDbContext(options);
            var productService = new ProductsService(dbContext);

            var productName = "USB";

            dbContext.Products.AddRange(new List <Product>
            {
                new Product {
                    Name = productName
                },
                new Product {
                    Name = "Cable"
                },
                new Product {
                    Name = "Keyboard"
                },
                new Product {
                    Name = "Computer"
                },
            });
            dbContext.SaveChanges();

            var product = dbContext.Products.FirstOrDefault(x => x.Name == productName);

            var isProductHide = productService.HideProduct(product.Id);

            Assert.True(isProductHide);
            Assert.True(product.Hide);
        }
        public void AddReviewShouldAddReview(int rating, int expected)
        {
            var options = new DbContextOptionsBuilder <XeonDbContext>()
                          .UseInMemoryDatabase(databaseName: $"AddReviews_Product_Database")
                          .Options;

            var dbContext      = new XeonDbContext(options);
            var productService = new ProductsService(dbContext);

            var parentCategory = new ParentCategory {
                Name = "Computers"
            };
            var childCategory = new ChildCategory {
                Name = "Cables", ParentCategory = parentCategory
            };

            dbContext.ChildCategories.Add(childCategory);
            dbContext.SaveChanges();

            var product = new Product {
                Name = "USB ", ChildCategory = childCategory
            };

            dbContext.Products.Add(product);
            dbContext.SaveChanges();

            productService.AddReview(rating, product.Id);

            Assert.Equal(expected, product.Reviews.Count());
        }
        public void ProductExistsShouldReturnFalse()
        {
            var options = new DbContextOptionsBuilder <XeonDbContext>()
                          .UseInMemoryDatabase(databaseName: "ProductNotExists_Product_Database")
                          .Options;

            var dbContext      = new XeonDbContext(options);
            var productService = new ProductsService(dbContext);

            dbContext.Products.AddRange(new List <Product>
            {
                new Product {
                    Name = "USB"
                },
                new Product {
                    Name = "Cable"
                },
                new Product {
                    Name = "Keyboard"
                },
                new Product {
                    Name = "Computer"
                },
            });
            dbContext.SaveChanges();

            var invalidProductId = 123;
            var isProductExist   = productService.ProductExists(invalidProductId);

            Assert.False(isProductExist);
        }
        public void HideInvalidProducShouldReturnFalse()
        {
            var options = new DbContextOptionsBuilder <XeonDbContext>()
                          .UseInMemoryDatabase(databaseName: "RemoveInvalid_Product_Database")
                          .Options;

            var dbContext      = new XeonDbContext(options);
            var productService = new ProductsService(dbContext);

            dbContext.Products.AddRange(new List <Product>
            {
                new Product {
                    Name = "USB"
                },
                new Product {
                    Name = "Cable"
                },
                new Product {
                    Name = "Keyboard"
                },
                new Product {
                    Name = "Computer"
                },
            });
            dbContext.SaveChanges();

            var invalidProductId = 123;
            var isProductDeleted = productService.HideProduct(invalidProductId);

            Assert.False(isProductDeleted);
            Assert.Equal(4, dbContext.Products.Count());
        }
        public void GetAllProductsShouldReturnAllProducts()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: "GetAll_Product_Database")
                          .Options;

            var dbContext = new ApplicationDbContext(options);

            var productsService = new ProductsService(dbContext, null, null);

            var products = new List <Product>()
            {
                new Product {
                    Name = "Ball"
                }, new Product {
                    Name = "Bike"
                }, new Product {
                    Name = "Bottle"
                }
            };

            dbContext.Products.AddRange(products);
            dbContext.SaveChanges();

            var result = productsService.GetAllProducts();

            Assert.Equal(products, result);
        }
        public void CreateProductShouldReturnTheCreatedProduct()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: "CreateProduct_Product_Database")
                          .Options;

            var dbContext = new ApplicationDbContext(options);

            var imageService = new Mock <IImageService>();

            imageService.Setup(x => x.AddImageToProduct(It.IsAny <IFormFile>())).Returns(new ProductImage()
            {
                PublicId = "PublicId",
                Id       = Convert.ToString(Guid.NewGuid()),
                ImageUrl = "http://www.url.com/",
            });


            var productsService = new ProductsService(dbContext, null, imageService.Object);

            var product = productsService.CreateProduct("Topka", "Kon", 123, GenerateFile(), "Mlqko");

            Assert.IsType <Product>(product);
            Assert.Equal("Topka", product.Name);
        }
        public void EditProductShouldNotEditTheProduct()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: "EditProduct_Products_Db")
                          .Options;

            var dbContext = new ApplicationDbContext(options);

            var productsService = new ProductsService(dbContext, null, null);


            var product = new Product
            {
                Name           = "Ball",
                Description    = "long description",
                IsHidden       = false,
                AdditionalInfo = null,
                Price          = 99
            };


            dbContext.Products.Add(product);
            dbContext.SaveChanges();

            var result = productsService.EditProduct("123sddsad", null, "short", true, "yes", 20);

            Assert.Null(result);
        }
示例#18
0
        public void Setup()
        {
            _mapperMock           = new Mock <IMapper>(MockBehavior.Strict);
            _productsProviderMock = new Mock <IProductsProvider>(MockBehavior.Strict);

            _productsService = new ProductsService(
                _productsProviderMock.Object,
                _mapperMock.Object);

            _mapperMock
            .Setup(x => x.Map <IQueryable <ProductEntity>, IEnumerable <Product> >(It.IsAny <IQueryable <ProductEntity> >()))
            .Returns(_models);
            _mapperMock
            .Setup(x => x.Map <Product>(It.IsAny <ProductEntity>()))
            .Returns(_model);
            _mapperMock
            .Setup(x => x.Map <ProductEntity>(It.IsAny <Product>()))
            .Returns(_entity);

            _productsProviderMock
            .Setup(x => x.GetAll())
            .Returns(_entities.AsQueryable());
            _productsProviderMock
            .Setup(x => x.GetById(It.IsAny <int>()))
            .Returns(_entity);
            _productsProviderMock
            .Setup(x => x.Create(It.IsAny <ProductEntity>()))
            .Returns(_entity);
            _productsProviderMock
            .Setup(x => x.Update(It.IsAny <ProductEntity>()))
            .Returns(_entity);
            _productsProviderMock
            .Setup(x => x.Delete(It.IsAny <int>()))
            .Verifiable();
        }
示例#19
0
        public CoinbaseProClient(
            IAuthenticator authenticator,
            IHttpClient httpClient,
            bool sandBox = false)
        {
            var clock = new Clock();
            var httpRequestMessageService = new HttpRequestMessageService(authenticator, clock, sandBox);
            var createWebSocketFeed       = (Func <IWebSocketFeed>)(() => new WebSocketFeed(sandBox));
            var queryBuilder = new QueryBuilder();

            AccountsService              = new AccountsService(httpClient, httpRequestMessageService);
            CoinbaseAccountsService      = new CoinbaseAccountsService(httpClient, httpRequestMessageService);
            OrdersService                = new OrdersService(httpClient, httpRequestMessageService, queryBuilder);
            PaymentsService              = new PaymentsService(httpClient, httpRequestMessageService);
            WithdrawalsService           = new WithdrawalsService(httpClient, httpRequestMessageService);
            DepositsService              = new DepositsService(httpClient, httpRequestMessageService);
            ProductsService              = new ProductsService(httpClient, httpRequestMessageService, queryBuilder);
            CurrenciesService            = new CurrenciesService(httpClient, httpRequestMessageService);
            FillsService                 = new FillsService(httpClient, httpRequestMessageService);
            FundingsService              = new FundingsService(httpClient, httpRequestMessageService, queryBuilder);
            ReportsService               = new ReportsService(httpClient, httpRequestMessageService);
            UserAccountService           = new UserAccountService(httpClient, httpRequestMessageService);
            StablecoinConversionsService = new StablecoinConversionsService(httpClient, httpRequestMessageService);
            FeesService     = new FeesService(httpClient, httpRequestMessageService);
            ProfilesService = new ProfilesService(httpClient, httpRequestMessageService);
            WebSocket       = new WebSocket.WebSocket(createWebSocketFeed, authenticator, clock);

            Log.Information("CoinbaseProClient constructed");
        }
示例#20
0
        public ActionResult Index()
        {
            var wishlist            = ProductWishlistService.GetListWishlist(AuthenticationHelper.CurrentUser);
            var listProductWishlist = ProductsService.GetListProductWishlist(wishlist);

            return(View("Wishlist.Index", listProductWishlist));
        }
示例#21
0
        public void When_Get_Product_With_Id_2_Then_Show_Only_This_Product()
        {
            var _productOptions = new DbContextOptionsBuilder <ProductsContext>().UseInMemoryDatabase("products_detail").Options;
            var _productContext = new ProductsContext(_productOptions);

            ProductsModel productData = new ProductsModel {
                id                = 2,
                name              = "43 Piece dinner Set",
                price             = (Decimal)12.95,
                availability      = "InStock",
                stockAvailability = 10,
                age               = "3_to_5",
                gender            = "FEMALE",
                brand             = "CoolKidz"
            };

            _productContext.Products.Add(productData);
            _productContext.SaveChanges();

            ProductsService productsService = new ProductsService(_productContext);
            var             actualResult    = productsService.getProductDetail(2);

            var expectedResult = _productContext.Products.First();

            Assert.Equal(expectedResult, actualResult);
        }
示例#22
0
        public async Task GetBaseByIdShouldReturnProduct()
        {
            var dbContext       = ApplicationDbContextInMemoryFactory.InitializeContext();
            var repository      = new EfDeletableEntityRepository <Product>(dbContext);
            var productsService = new ProductsService(repository);

            // Create
            var product = new Product()
            {
                Name        = "TestProduct",
                Description = "none",
                CategoryId  = 3,
                Category    = new Category()
                {
                    Id = 1, Name = "Test Category "
                },
                ImageUrl         = null,
                ImageStorageName = null,
                Ratings          = null,
            };
            await productsService.CreateAsync(product);

            // Get
            var productsFromDb = await productsService.GetBaseById(product.Id);

            Assert.Equal(product.Id, productsFromDb.Id);
        }
示例#23
0
        public async Task Clear_OneOfTwoBaskets()
        {
            var prodRepo        = new MockRepository <Product>();
            var basketRepo      = new MockRepository <ProductInBasket>();
            var productsService = new ProductsService(prodRepo);
            var basketService   = new BasketService(basketRepo, productsService);

            var userId      = "UserA";
            var otherUserId = "UserB";

            basketService.Add(new ProductInBasket {
                Id = 1, ProductId = 2, UserId = userId, Count = 50
            });
            basketService.Add(new ProductInBasket {
                Id = 1, ProductId = 4, UserId = userId, Count = 2
            });
            basketService.Add(new ProductInBasket {
                Id = 2, ProductId = 2, UserId = otherUserId, Count = 50
            });

            basketService.Clear(userId);

            Assert.True(basketService.ItemsCount(userId) == 0);
            Assert.True(basketService.ItemsCount(otherUserId) == 50);
        }
示例#24
0
        public async Task GetAllShouldReturnCorrectProducts()
        {
            var productsRepository = new Mock <IDeletableEntityRepository <Product> >();

            productsRepository.Setup(r => r.All()).Returns(new List <Product>
            {
                new Product()
                {
                    CategoryId = 1,
                },
                new Product()
                {
                    CategoryId = 2,
                },
                new Product()
                {
                    CategoryId = 3,
                },
            }.AsQueryable());

            var productsService = new ProductsService(productsRepository.Object);

            var productsFromCategory =
                await productsService.GetAll <Product>();

            var count        = productsFromCategory.Count();
            var firstProduct = productsFromCategory.First();

            Assert.Equal(3, count);
            Assert.Equal(1, firstProduct.CategoryId);
        }
        public async Task CheckGettingProductIdByNameAsync()
        {
            ApplicationDbContext db = GetDb();

            var repository = new EfDeletableEntityRepository <Product>(db);
            var service    = new ProductsService(
                repository,
                this.clientProductLikesRepository.Object,
                this.cloudinaryService.Object);

            var firstProduct = new Product()
            {
                Id   = "1",
                Name = "firstProductName",
            };

            var secondProduct = new Product()
            {
                Id   = "2",
                Name = "secondProductName",
            };

            await db.Products.AddAsync(firstProduct);

            await db.Products.AddAsync(secondProduct);

            await db.SaveChangesAsync();

            var productId = await service.GetProductIdByNameAsync(firstProduct.Name);

            Assert.Equal(firstProduct.Id, productId);
        }
示例#26
0
        public async Task Given_Response_Is_Forbidden_When_Retrieving_Products_Then_Log_The_Exception()
        {
            // Arrange
            using var server        = WireMockServer.Start();
            _httpClient.BaseAddress = new Uri($"http://localhost:{server.Ports[0]}");

            server
            .Given(Request.Create().WithPath("/api/Products").UsingGet())
            .RespondWith(Response.Create().WithStatusCode(403));

            var productsService = new ProductsService(
                _httpClient,
                _mockLogger.Object);

            // Act
            await productsService.ListProductsAsync();

            // Assert
            _mockLogger.Verify(x => x.Log(
                                   It.IsAny <LogLevel>(),
                                   It.IsAny <EventId>(),
                                   It.Is <It.IsAnyType>((o, t) => true),
                                   It.IsAny <Exception>(),
                                   It.Is <Func <It.IsAnyType, Exception, string> >((o, t) => true)), Times.Once);
        }
示例#27
0
        public IActionResult Edit(HttpResponse response, HttpSession session,
                                  EditProductBindingModel model, int knifeId)
        {
            var user = AuthenticationManager.GetAuthenticatedUser(session.Id);

            if (user == null)
            {
                this.Redirect(response, "/login/login");
                return(null);
            }

            var service = new ProductsService(Data.Data.Context);

            var knife = service.IsKnifeIdExist(knifeId);

            if (knife == null)
            {
                this.Redirect(response, "/home/index");
                return(null);
            }

            service.Update(model, knifeId);

            this.Redirect(response, "/admin/index");
            return(null);
        }
        public async Task GetAllProducts_ReturnsAvailableProducts_UsingBogus()
        {
            // Arrange
            var id    = 1;
            var names = new[] { "laptop", "xbox", "TV", "smartphone", "tablet" };
            var faker = new Faker <Product>()
                        .RuleFor(p => p.Id, f => id++)
                        .RuleFor(p => p.Name, f => f.PickRandom(names));

            IEnumerable <Product> products = faker.Generate(100);

            //var faker2 = new Faker<Product>()
            //                   .RuleFor(p => p.Id, f => f.Random.Int())
            //                   .RuleFor(p => p.Name, f => f.Random.String());

            _mockProductsRepository.Setup(x => x.GetAllProducts()).Returns(Task.FromResult(products));

            var sut = new ProductsService(_mockProductsRepository.Object);

            // Act
            var actual = await sut.GetAllProducts();

            // Assert
            Assert.True(actual.ToList().Count > 0);
        }
        public void AddProduct_WhenInput_IsValid()
        {
            //Arrange
            var options = new DbContextOptionsBuilder <GameStoreContext>()
                          .UseInMemoryDatabase("AddProduct_WhenInput_IsValid").Options;

            var productToAdd = new Product
            {
                Name                 = "Test",
                Description          = "test description",
                ShoppingCartProducts = new List <ShoppingCartProducts>(),
                Comments             = new List <Comment>()
            };

            //Act
            using (var curContext = new GameStoreContext(options))
            {
                var sut = new ProductsService(curContext);
                curContext.Products.Add(productToAdd);
                curContext.SaveChanges();
            }


            //Assert
            using (var curContext = new GameStoreContext(options))
            {
                Assert.IsTrue(curContext.Products.Count() == 1);
            }
        }
        //ToDO
        public async void ThrowException_WhenInput_AlreadyExists()
        {
            //Arrange
            var options = new DbContextOptionsBuilder <GameStoreContext>()
                          .UseInMemoryDatabase("ThrowException_WhenInput_AlreadyExists").Options;

            var productToAdd = new Product
            {
                Name                 = "Test",
                Description          = "test description",
                ShoppingCartProducts = new List <ShoppingCartProducts>(),
                Comments             = new List <Comment>()
            };

            //Act
            using (var curContext = new GameStoreContext(options))
            {
                var sut = new ProductsService(curContext);
                curContext.Products.Add(productToAdd);

                curContext.SaveChanges();
            }

            //Act
            using (var curContext = new GameStoreContext(options))
            {
                var sut = new ProductsService(curContext);
                await sut.AddProductAsync(productToAdd);
            }
        }
	public void WhenQueryingOverLimit_ThenGetsLimitedResults()
	{
		var baseUri = new Uri("http://localhost:20000");
		var service = new ProductsService();
		var config = HttpHostConfiguration.Create()
			.SetResourceFactory(new SingletonResourceFactory(service))
			.AddMessageHandlers(typeof(TracingChannel));

		using (new SafeHostDisposer(
			new HttpQueryableServiceHost(typeof(ProductsService), 25, config, new Uri(baseUri, "products"))))
		{
			var client = new HttpEntityClient(baseUri);
			var query = (IHttpEntityQuery<Product>)client.Query<Product>("products").Skip(10).Take(50);

			var result = query.Execute();

			Assert.Equal(100, result.TotalCount);
			Assert.Equal(25, result.Count());
			Assert.Equal(10, result.First().Id);
		}
	}
示例#32
0
 public ProductsViewComponent(ProductsService productsService, IMemoryCache cache)
 {
     ProductsService = productsService;
     Cache = cache;
 }
示例#33
0
        public void Initialize()
        {
            //TODO: 15-Mar-2013 - Ben - seems hacky rebuilding container. I should just be able to override the mock provider instance each time. Seems to only remember the first time.
            // to replicate remove the IoC.BuildContainer() line and run all tests. The mock instance is only registered once for some reason.
            // come back to this one when you know a bit more.
            IoC.BuildContainer();

            var builder = new ContainerBuilder();
            _mockProvider = new Mock<IProductsProvider>();

            builder.RegisterInstance(new Mock<DbContext>().Object);
            builder.RegisterInstance(_mockProvider.Object);
            builder.Update(IoC.Container);

            var scope = IoC.Container.BeginLifetimeScope();
            _service = scope.Resolve<ProductsService>();
        }
	public void WhenQueryingRepeatedArgument_ThenServiceGetsBoth()
	{
		var baseUri = new Uri("http://localhost:20000");
		var service = new ProductsService();
		var config = HttpHostConfiguration.Create()
			.SetResourceFactory(new SingletonResourceFactory(service))
			.UseJsonNet()
			.AddMessageHandlers(typeof(TracingChannel));

		using (new SafeHostDisposer(
			new HttpQueryableServiceHost(typeof(ProductsService), 25, config, new Uri(baseUri, "products"))))
		{
			var client = new HttpEntityClient(baseUri);
			var query = (IHttpEntityQuery<Product>)client.Query<Product>("products/search2",
				new HttpNameValueCollection { { "search", "10" }, { "search", "20" }, { "count", "25" } });

			var result = query.Execute();

			Assert.Equal(2, result.TotalCount);
			Assert.Equal(2, result.Count());
			Assert.Equal(10, result.First().Id);
		}
	}