Разработка интернет-магазина на технологии ASP.NET MVC 3
Характеристика и анализ технологии ASP.NET. Анализ средств разработки и программных продуктов в сфере интернет, обоснование их выбора. Разработка логической, физической модели базы данных, схемы информационно-справочной системы. Руководство пользователя.
Рубрика | Программирование, компьютеры и кибернетика |
Вид | курсовая работа |
Язык | русский |
Дата добавления | 17.06.2013 |
Размер файла | 1,6 M |
Отправить свою хорошую работу в базу знаний просто. Используйте форму, расположенную ниже
Студенты, аспиранты, молодые ученые, использующие базу знаний в своей учебе и работе, будут вам очень благодарны.
}
}
}
using System. Collections. Generic;
using SportsStore. Domain. Entities;
namespace SportsStore. WebUI. Models {
public class ProductsListViewModel {
public IEnumerable<Product> Products {get; set;}
public PagingInfo PagingInfo {get; set;}
public string CurrentCategory {get; set;}
public string query {get; set;}
}
}
using System;
using System. Collections. Generic;
using System. Linq;
using System. Web;
using System. Web. Mvc;
using System. Web. Routing;
using SportsStore. WebUI. Infrastructure;
using SportsStore. WebUI. Binders;
using SportsStore. Domain. Entities;
namespace SportsStore. WebUI {
// Note: For instructions on enabling rw6 or IIS7 classic mode,
// visit http://go.microsoft.com/? LinkId=9394801
public class MvcApplication: System. Web. HttpApplication {
public static void RegisterGlobalFilters (GlobalFilterCollection filters) {
filters. Add (new HandleErrorAttribute());
}
public static void RegisterRoutes (RouteCollection routes) {
routes. IgnoreRoute(«{resource}.axd/{*pathInfo}»);
routes. MapRoute (null,
«», // Only matches the empty URL (i.e. /)
new {
controller = «Product», action = «List»,
category = (string) null, page = 1
}
);
routes. MapRoute (null,
«Page{page}», // Matches /Page2, /Page123, but not /PageXYZ
new {controller = «Product», action = «List», category = (string) null},
new {page = @»\d+»} // Constraints: page must be numerical
);
routes. MapRoute (null,
«{category}», // Matches /Football or /AnythingWithNoSlash
new {controller = «Product», action = «List», page = 1}
);
routes. MapRoute (null,
«{category}/Page{page}», // Matches /Football/Page567
new {controller = «Product», action = «List»}, // Defaults
new {page = @»\d+»} // Constraints: page must be numerical
);
routes. MapRoute (null, «{controller}/{action}»);
}
protected void Application_Start() {
AreaRegistration. RegisterAllAreas();
RegisterGlobalFilters (GlobalFilters. Filters);
RegisterRoutes (RouteTable. Routes);
ControllerBuilder. Current. SetControllerFactory (new NinjectControllerFactory());
ModelBinders. Binders. Add (typeof(Cart), new CartModelBinder());
}
}
}
Web.config
<? xml version= «1.0»?>
<!-
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/? LinkId=152368
->
<configuration>
<connectionStrings>
<add name= «EFDbContext» connectionString= «Data Source=.\SQLEXPRESS; Initial Catalog=SportsStore; integrated security=True; pooling=False;»
providerName= «System. Data. SqlClient»/>
</connectionStrings>
<appSettings>
<add key= «ClientValidationEnabled» value= «true»/>
<add key= «UnobtrusiveJavaScriptEnabled» value= «true»/>
<add key= «Email. WriteAsFile» value= «true»/>
</appSettings>
<system.web>
<globalization culture= «en-US» uiCulture= «en-US»/>
<compilation debug= «true» targetFramework= «4.0»>
<assemblies>
<add assembly= «System. Web. Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35»/>
<add assembly= «System. Web. Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35»/>
<add assembly= «System. Web. Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35»/>
<add assembly= «System. Web. Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35»/>
<add assembly= «System. Web. WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35»/>
</assemblies>
</compilation>
<authentication mode= «Forms»>
<forms loginUrl= "~/Account/LogOn» timeout= «2880»>
<credentials passwordFormat= «Clear»>
<user name= «Roman» password= «123» />
</credentials>
</forms>
</authentication>
<pages>
<namespaces>
<add namespace= «System. Web. Helpers»/>
<add namespace= «System. Web. Mvc»/>
<add namespace= «System. Web. Mvc. Ajax»/>
<add namespace= «System. Web. Mvc. Html»/>
<add namespace= «System. Web. Routing»/>
<add namespace= «System. Web. WebPages»/>
</namespaces>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration= «false»/>
<modules runAllManagedModulesForAllRequests= «true»/>
</system.webServer>
<runtime>
<assemblyBinding xmlns= «urn:schemas-microsoft-com:asm.v1»>
<dependentAssembly>
<assemblyIdentity name= «System. Web. Mvc» publicKeyToken= «31bf3856ad364e35»/>
<bindingRedirect oldVersion= «1.0.0.0-2.0.0.0» newVersion= «3.0.0.0»/>
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
Приложение Б
Исходный код разметки страниц
// Shared/_ProductSummary.cshtml
@model SportsStore. Domain. Entities. Product
<div class= «item»>
@if (Model. ImageData!= null) {
<div style= «float:left; margin-right:20px»>
<img width= «75» height= «75» src="@Url. Action («GetImage», «Product»,
new {Model. ProductID})» />
</div>
}
<h3>@Model. Name</h3>
@Model. Description
<div class= «item»>
@using (Html. BeginForm («AddToCart», «Cart»)) {
@Html. HiddenFor (x => x. ProductID)
@Html. Hidden («returnUrl», Request. Url. PathAndQuery)
<input type= «submit» value= "+ Add to cart» />
}
</div>
<h4>@Model. Price. ToString («c»)</h4>
</div>
// Shared/_error.cshtml
@{
Layout = null;
}
<! DOCTYPE html>
<html>
<head>
<title>Error</title>
</head>
<body>
<h2>
Sorry, an error occurred while processing your request.
</h2>
</body>
</html>
// Shared/__ViewStart.cshtml
@{
Layout = «~/Views/Shared/_Layout.cshtml»;
}
// Shared/__Layout.cshtml
<! DOCTYPE html>
<html>
<head>
<title>@ViewBag. Title</title>
<link href="@Url. Content («~/Content/Site.css»)» rel= «stylesheet» type= «text/css» />
<script src="@Url. Content («~/Scripts/jquery-1.4.4.min.js»)» type= «text/javascript»></script>
</head>
<body>
<div id= «header»>
@{Html. RenderAction («Summary», «Cart»);}
<div class= «title»>This is your store</div>
</div>
<div id= «categories»>
@{Html. RenderAction («Menu», «Nav»);}
</div>
<div id= «content»>
@RenderBody()
</div>
</body>
</html>
//Shared/_AdminLayout.cshtml
<! DOCTYPE html>
<html>
<head>
<title>@ViewBag. Title</title>
<link href="@Url. Content («~/Content/Admin.css»)» rel= «stylesheet» type= «text/css» />
<script src="@Url. Content («~/Scripts/jquery-1.4.4.min.js»)»
type= «text/javascript»></script>
<script src="@Url. Content («~/Scripts/jquery.validate.min.js»)»
type= «text/javascript»></script>
<script src="@Url. Content («~/Scripts/jquery.validate.unobtrusive.min.js»)»
type= «text/javascript»></script>
</head>
<body>
<div>
@if (TempData [«message»]!= null) {
<div class= «Message»>@TempData [«message»]</div>
}
@RenderBody()
</div>
</body>
</html>
//Product/List.cshtml
@model SportsStore. WebUI. Models. ProductsListViewModel
@{
ViewBag. Title = «Products»;
}
@foreach (var p in Model. Products) {
Html. RenderPartial («ProductSummary», p);
}
<div class= «pager»>
@Html. PageLinks (Model. PagingInfo, x => Url. Action («List»,
new {page = x, category = Model. CurrentCategory}))
</div>
//Nav/Menu.cshtml
@model IEnumerable<string>
@{
Layout = null;
}
@Html. ActionLink («All product», «List», «Product»)
@foreach (var link in Model) {
@Html. RouteLink (link,
new {
controller = «Product»,
action = «List»,
category = link,
page = 1
},
new {
@class = link == ViewBag. SelectedCategory? «selected»: null
}
)
}
//Cart/Summary.cshtml
@model SportsStore. Domain. Entities. Cart
@{
Layout = null;
}
<div id= «cart»>
<span class= «caption»>
<b>Your cart:</b>
@Model. Lines. Sum (x => x. Quantity) item(s),
@Model. ComputeTotalValue().ToString («c»)
</span>
@Html. ActionLink («Checkout», «Index», «Cart»,
new {returnUrl = Request. Url. PathAndQuery}, null)
</div>
//Cart/Index.cshtml
@model SportsStore. WebUI. Models. CartIndexViewModel
@{
ViewBag. Title = «Sports Store: Your Cart»;
}
<h2>Your cart</h2>
<table width= «90%» align= «center»>
<thead><tr>
<th align= «center»>Quantity</th>
<th align= «left»>Item</th>
<th align= «right»>Price</th>
<th align= «right»>Subtotal</th>
</tr></thead>
<tbody>
@foreach (var line in Model. Cart. Lines) {
<tr>
<td align= «center»>@line. Quantity</td>
<td align= «left»>@line. Product. Name</td>
<td align= «right»>@line. Product. Price. ToString («c»)</td>
<td align= «right»>@((line. Quantity * line. Product. Price).ToString («c»))</td>
<td>
@using (Html. BeginForm («RemoveFromCart», «Cart»)) {
@Html. Hidden («ProductId», line. Product. ProductID)
@Html. HiddenFor (x => x. ReturnUrl)
<input class= «actionButtons» type= «submit» value= «Remove» />
}
</td>
</tr>
}
</tbody>
<tfoot><tr>
<td colspan= «3» align= «right»>Total:</td>
<td align= «right»>
@Model. Cart. ComputeTotalValue().ToString («c»)
</td>
</tr></tfoot>
</table>
<p align= «center» class= «actionButtons»>
<a href= "@Model. ReturnUrl»>Continue shopping</a>
@Html. ActionLink («Checkout now», «Checkout»)
</p>
//Cart/Completed.cshtml
@{
ViewBag. Title = «SportsStore: Order Submitted»;
}
<h2>Thanks!</h2>
Thanks for placing your order. We'll ship your goods as soon as possible.
//Cart/Checkout.cshtml
@model SportsStore. Domain. Entities. ShippingDetails
@{
ViewBag. Title = «SportStore: Checkout»;
}
<h2>Check out now</h2>
Please enter your details, and we'll ship your goods right away!
@using (Html. BeginForm()) {
@Html. ValidationSummary()
<h3>Ship to</h3>
<div>Name: @Html. EditorFor (x => x. Name)</div>
<h3>Options</h3>
<label>
@Html. EditorFor (x => x. GiftWrap)
Gift wrap these items
</label>
<h3>Address</h3>
<div>@Html. EditorFor (x => x. Line1) Phone number</div>
<div>@Html. EditorFor (x => x. Line2) Home number</div>
<div>@Html. EditorFor (x => x. Line3) Street</div>
<div>@Html. EditorFor (x => x. City) City</div>
<div>@Html. EditorFor (x => x. State) State</div>
<div>@Html. EditorFor (x => x. Zip) Zip</div>
<div>@Html. EditorFor (x => x. Country) Country</div>
<p align= «center»>
<input type= «submit» class= «actionButtons» value= «Complete order» />
</p>
}
//Admin/Index.cshtml
@model IEnumerable<SportsStore. Domain. Entities. Product>
@{
ViewBag. Title = «Admin: All Products»;
Layout = «~/Views/Shared/_AdminLayout.cshtml»;
}
<h1>All Products</h1>
<table class= «Grid»>
<tr>
<th>ID</th>
<th>Name</th>
<th class= «NumericCol»>Price</th>
<th>Actions</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>@item. ProductID</td>
<td>@Html. ActionLink (item. Name, «Edit», new {item. ProductID})</td>
<td class= «NumericCol»>@item. Price. ToString («c»)</td>
<td>
@using (Html. BeginForm («Delete», «Admin»)) {
@Html. Hidden («ProductID», item. ProductID)
<input type= «submit» value= «Delete»/>
}
</td>
</tr>
}
</table>
<p>@Html. ActionLink («Add a new product», «Create»)</p>
//Admin/Edit.cshtml
@model SportsStore. Domain. Entities. Product
@{
ViewBag. Title = «Admin: Edit» + @Model. Name;
Layout = «~/Views/Shared/_AdminLayout.cshtml»;
}
<h1>Edit @Model. Name</h1>
@using (Html. BeginForm («Edit», «Admin», FormMethod. Post,
new {enctype = «multipart/form-data»})) {
@Html. EditorForModel()
<div class= «editor-label»>Image</div>
<div class= «editor-field»>
@if (Model. ImageData == null) {
@:None
} else {
<img width= «150» height= «150»
src="@Url. Action («GetImage», «Product», new {Model. ProductID})» />
}
<div>Upload new image: <input type= «file» name= «Image» /></div>
</div>
<input type= «submit» value= «Save» />
@Html. ActionLink («Cancel and return to List», «Index»)
}
//Account/LogOn.cshtml
@model SportsStore. WebUI. Models. LogOnViewModel
@{
ViewBag. Title = «Admin: Log In»;
Layout = «~/Views/Shared/_AdminLayout.cshtml»;
}
<h1>Log In</h1>
<p>Please log in to access the administrative area:</p>
@using (Html. BeginForm()) {
@Html. ValidationSummary(true)
@Html. EditorForModel()
<p><input type= «submit» value= «Log in» /></p>
Приложение В
Листинг модельных тестов
using SportsStore. WebUI. Controllers;
using Microsoft. VisualStudio. TestTools. UnitTesting;
using System;
using Microsoft. VisualStudio. TestTools. UnitTesting. Web;
using SportsStore. WebUI. Models;
using System. Web. Mvc;
using System. Web. Security;
using Moq;
using SportsStore. WebUI. Infrastructure. Abstract;
namespace SportsStore. UnitTests
{
[TestClass()]
public class AccountControllerTest {
[TestMethod]
public void Can_Login_With_Valid_Credentials() {
// Arrange - create a mock authentication provider
Mock<IAuthProvider> mock = new Mock<IAuthProvider>();
mock. Setup (m => m. Authenticate («admin», «secret»)).Returns(true);
// Arrange - create the view model
LogOnViewModel model = new LogOnViewModel {
UserName = «admin»,
Password = «secret»
};
// Arrange - create the controller
AccountController target = new AccountController (mock. Object);
// Act - authenticate using valid credentials
ActionResult result = target. LogOn (model, «/MyURL»);
// Assert
Assert. IsInstanceOfType (result, typeof(RedirectResult));
Assert. AreEqual («/MyURL», ((RedirectResult) result).Url);
}
[TestMethod]
public void Cannot_Login_With_Invalid_Credentials() {
// Arrange - create a mock authentication provider
Mock<IAuthProvider> mock = new Mock<IAuthProvider>();
mock. Setup (m => m. Authenticate («badUser», «badPass»)).Returns(false);
// Arrange - create the view model
LogOnViewModel model = new LogOnViewModel {
UserName = «badUser»,
Password = «badPass»
};
// Arrange - create the controller
AccountController target = new AccountController (mock. Object);
// Act - authenticate using valid credentials
ActionResult result = target. LogOn (model, «/MyURL»);
// Assert
Assert. IsInstanceOfType (result, typeof(ViewResult));
Assert. IsFalse(((ViewResult) result).ViewData. ModelState. IsValid);
}
}
}
using System. Collections. Generic;
using System. Linq;
using Microsoft. VisualStudio. TestTools. UnitTesting;
using Moq;
using SportsStore. Domain. Abstract;
using SportsStore. Domain. Entities;
using SportsStore. WebUI. Controllers;
using System;
using Microsoft. VisualStudio. TestTools. UnitTesting. Web;
using System. Web. Mvc;
namespace SportsStore. UnitTests {
[TestClass()]
public class AdminControllerTest {
[TestMethod]
public void Index_Contains_All_Products() {
// Arrange - create the mock repository
Mock<IProductRepository> mock = new Mock<IProductRepository>();
mock. Setup (m => m. Products).Returns (new Product[] {
new Product {ProductID = 1, Name = «P1»},
new Product {ProductID = 2, Name = «P2»},
new Product {ProductID = 3, Name = «P3»},
}.AsQueryable());
// Arrange - create a controller
AdminController target = new AdminController (mock. Object);
// Action
Product[] result = ((IEnumerable<Product>) target. Index().ViewData. Model).ToArray();
// Assert
Assert. AreEqual (result. Length, 3);
Assert. AreEqual («P1», result[0].Name);
Assert. AreEqual («P2», result[1].Name);
Assert. AreEqual («P3», result[2].Name);
}
[TestMethod]
public void Can_Edit_Product() {
// Arrange - create the mock repository
Mock<IProductRepository> mock = new Mock<IProductRepository>();
mock. Setup (m => m. Products).Returns (new Product[] {
new Product {ProductID = 1, Name = «P1»},
new Product {ProductID = 2, Name = «P2»},
new Product {ProductID = 3, Name = «P3»},
}.AsQueryable());
// Arrange - create the controller
AdminController target = new AdminController (mock. Object);
// Act
Product p1 = target. Edit(1).ViewData. Model as Product;
Product p2 = target. Edit(2).ViewData. Model as Product;
Product p3 = target. Edit(3).ViewData. Model as Product;
// Assert
Assert. AreEqual (1, p1. ProductID);
Assert. AreEqual (2, p2. ProductID);
Assert. AreEqual (3, p3. ProductID);
}
[TestMethod]
public void Cannot_Edit_Nonexistent_Product() {
// Arrange - create the mock repository
Mock<IProductRepository> mock = new Mock<IProductRepository>();
mock. Setup (m => m. Products).Returns (new Product[] {
new Product {ProductID = 1, Name = «P1»},
new Product {ProductID = 2, Name = «P2»},
new Product {ProductID = 3, Name = «P3»},
}.AsQueryable());
// Arrange - create the controller
AdminController target = new AdminController (mock. Object);
// Act
Product result = (Product) target. Edit(4).ViewData. Model;
// Assert
Assert. IsNull(result);
}
[TestMethod]
public void Can_Save_Valid_Changes() {
// Arrange - create mock repository
Mock<IProductRepository> mock = new Mock<IProductRepository>();
// Arrange - create the controller
AdminController target = new AdminController (mock. Object);
// Arrange - create a product
Product product = new Product {Name = «Test»};
// Act - try to save the product
ActionResult result = target. Edit (product, null);
// Assert - check that the repository was called
mock. Verify (m => m. SaveProduct(product));
// Assert - check the method result type
Assert. IsNotInstanceOfType (result, typeof(ViewResult));
}
[TestMethod]
public void Cannot_Save_Invalid_Changes() {
// Arrange - create mock repository
Mock<IProductRepository> mock = new Mock<IProductRepository>();
// Arrange - create the controller
AdminController target = new AdminController (mock. Object);
// Arrange - create a product
Product product = new Product {Name = «Test»};
// Arrange - add an error to the model state
target. ModelState. AddModelError («error», «error»);
// Act - try to save the product
ActionResult result = target. Edit (product, null);
// Assert - check that the repository was not called
mock. Verify (m => m. SaveProduct (It. IsAny<Product>()), Times. Never());
// Assert - check the method result type
Assert. IsInstanceOfType (result, typeof(ViewResult));
}
[TestMethod]
public void Can_Delete_Valid_Products() {
// Arrange - create a Product
Product prod = new Product {ProductID = 2, Name = «Test»};
// Arrange - create the mock repository
Mock<IProductRepository> mock = new Mock<IProductRepository>();
mock. Setup (m => m. Products).Returns (new Product[] {
new Product {ProductID = 1, Name = «P1»},
prod,
new Product {ProductID = 3, Name = «P3»},
}.AsQueryable());
// Arrange - create the controller
AdminController target = new AdminController (mock. Object);
// Act - delete the product
target. Delete (prod. ProductID);
// Assert - ensure that the repository delete method was
// called with the correct Product
mock. Verify (m => m. DeleteProduct(prod));
}
[TestMethod]
public void Cannot_Delete_Invalid_Products() {
// Arrange - create the mock repository
Mock<IProductRepository> mock = new Mock<IProductRepository>();
mock. Setup (m => m. Products).Returns (new Product[] {
new Product {ProductID = 1, Name = «P1»},
new Product {ProductID = 2, Name = «P2»},
new Product {ProductID = 3, Name = «P3»},
}.AsQueryable());
// Arrange - create the controller
AdminController target = new AdminController (mock. Object);
// Act - delete using an ID that doesn't exist
target. Delete(100);
// Assert - ensure that the repository delete method was
// called with the correct Product
mock. Verify (m => m. DeleteProduct (It. IsAny<Product>()), Times. Never());
}
}
}
using System. Linq;
using Microsoft. VisualStudio. TestTools. UnitTesting;
using Moq;
using SportsStore. Domain. Abstract;
using SportsStore. Domain. Entities;
using SportsStore. WebUI. Controllers;
using System. Web. Mvc;
using SportsStore. WebUI. Models;
namespace SportsStore. UnitTests {
[TestClass()]
public class CartControllerTest {
[TestMethod]
public void Cannot_Checkout_Empty_Cart() {
// Arrange - create a mock order processor
Mock<IOrderProcessor> mock = new Mock<IOrderProcessor>();
// Arrange - create an empty cart
Cart cart = new Cart();
// Arrange - create shipping details
ShippingDetails shippingDetails = new ShippingDetails();
// Arrange - create an instance of the controller
CartController target = new CartController (null, mock. Object);
// Act
ViewResult result = target. Checkout (cart, shippingDetails);
// Assert - check that the order hasn't been passed on to the processor
mock. Verify (m => m. ProcessOrder (It. IsAny<Cart>(), It. IsAny<ShippingDetails>()),
Times. Never());
// Assert - check that the method is returning the default view
Assert. AreEqual («», result. ViewName);
// Assert - check that we are passing an invalid model to the view
Assert. AreEqual (false, result. ViewData. ModelState. IsValid);
}
[TestMethod]
public void Cannot_Checkout_Invalid_ShippingDetails() {
// Arrange - create a mock order processor
Mock<IOrderProcessor> mock = new Mock<IOrderProcessor>();
// Arrange - create a cart with an item
Cart cart = new Cart();
cart. AddItem (new Product(), 1);
// Arrange - create an instance of the controller
CartController target = new CartController (null, mock. Object);
// Arrange - add an error to the model
target. ModelState. AddModelError («error», «error»);
// Act - try to checkout
ViewResult result = target. Checkout (cart, new ShippingDetails());
// Assert - check that the order hasn't been passed on to the processor
mock. Verify (m => m. ProcessOrder (It. IsAny<Cart>(), It. IsAny<ShippingDetails>()),
Times. Never());
// Assert - check that the method is returning the default view
Assert. AreEqual («», result. ViewName);
// Assert - check that we are passing an invalid model to the view
Assert. AreEqual (false, result. ViewData. ModelState. IsValid);
}
[TestMethod]
public void Can_Checkout_And_Submit_Order() {
// Arrange - create a mock order processor
Mock<IOrderProcessor> mock = new Mock<IOrderProcessor>();
// Arrange - create a cart with an item
Cart cart = new Cart();
cart. AddItem (new Product(), 1);
// Arrange - create an instance of the controller
CartController target = new CartController (null, mock. Object);
// Act - try to checkout
ViewResult result = target. Checkout (cart, new ShippingDetails());
// Assert - check that the order has been passed on to the processor
mock. Verify (m => m. ProcessOrder (It. IsAny<Cart>(), It. IsAny<ShippingDetails>()),
Times. Once());
// Assert - check that the method is returning the Completed view
Assert. AreEqual («Completed», result. ViewName);
// Assert - check that we are passing an valid model to the view
Assert. AreEqual (true, result. ViewData. ModelState. IsValid);
}
[TestMethod]
public void AddToCartTest() {
// Arrange - create the mock repository
Mock<IProductRepository> mock = new Mock<IProductRepository>();
mock. Setup (m => m. Products).Returns (new Product[] {
new Product {ProductID = 1, Name = «P1», Category = «Apples»},
}.AsQueryable());
// Arrange - create a Cart
Cart cart = new Cart();
// Arrange - create the controller
CartController target = new CartController (mock. Object, null);
// Act - add a product to the cart
target. AddToCart (cart, 1, null);
// Assert
Assert. AreEqual (cart. Lines. Count(), 1);
Assert. AreEqual (cart. Lines. ToArray() [0].Product. ProductID, 1);
}
[TestMethod]
public void Adding_Product_To_Cart_Goes_To_Cart_Screen() {
// Arrange - create the mock repository
Mock<IProductRepository> mock = new Mock<IProductRepository>();
mock. Setup (m => m. Products).Returns (new Product[] {
new Product {ProductID = 1, Name = «P1», Category = «Apples»},
}.AsQueryable());
// Arrange - create a Cart
Cart cart = new Cart();
// Arrange - create the controller
CartController target = new CartController (mock. Object, null);
// Act - add a product to the cart
RedirectToRouteResult result = target. AddToCart (cart, 2, «myUrl»);
// Assert
Assert. AreEqual (result. RouteValues [«action»], «Index»);
Assert. AreEqual (result. RouteValues [«returnUrl»], «myUrl»);
}
[TestMethod]
public void Can_View_Cart_Contents() {
// Arrange - create a Cart
Cart cart = new Cart();
// Arrange - create the controller
CartController target = new CartController (null, null);
// Act - call the Index action method
CartIndexViewModel result
= (CartIndexViewModel) target. Index (cart, «myUrl»).ViewData. Model;
// Assert
Assert. AreSame (result. Cart, cart);
Assert. AreEqual (result. ReturnUrl, «myUrl»);
}
}
}
using SportsStore. Domain. Concrete;
using Microsoft. VisualStudio. TestTools. UnitTesting;
using System;
using SportsStore. Domain. Entities;
using System. Linq;
namespace SportsStore. UnitTests
{
[TestClass()]
public class EFProductRepositoryTest {
private TestContext testContextInstance;
public TestContext TestContext {
get {
return testContextInstance;
}
set {
testContextInstance = value;
}
}
#region Additional test attributes
//
//You can use the following additional attributes as you write your tests:
//
//Use ClassInitialize to run code before running the first test in the class
// [ClassInitialize()]
//public static void MyClassInitialize (TestContext testContext)
// {
// }
//
//Use ClassCleanup to run code after all tests in a class have run
// [ClassCleanup()]
//public static void MyClassCleanup()
// {
// }
//
//Use TestInitialize to run code before running each test
// [TestInitialize()]
//public void MyTestInitialize()
// {
// }
//
//Use TestCleanup to run code after each test has run
// [TestCleanup()]
//public void MyTestCleanup()
// {
// }
//
#endregion
[TestMethod]
public void SaveProductTest() {
// Arrange - create a repository
EFProductRepository target = new EFProductRepository();
// Act - change the category of the first product
Product prod = target. Products. First();
prod. Category = «Test»;
target. SaveProduct(prod);
}
}
}
using SportsStore. Domain. Concrete;
using Microsoft. VisualStudio. TestTools. UnitTesting;
using System;
using SportsStore. Domain. Entities;
namespace SportsStore. UnitTests {
[TestClass()]
public class EmailOrderProcessorTest {
[TestMethod]
public void Can_Send_Email() {
// Arrange - create and populate a cart
Cart cart = new Cart();
cart. AddItem (new Product {ProductID = 1, Name = «Banana», Price = 10M}, 2);
cart. AddItem (new Product {ProductID = 2, Name = «Apple», Price = 5M}, 2);
// Arrange - create and populate some shipping details
ShippingDetails shipDetails = new ShippingDetails {
Name = «Joe Smith»,
Line1 = «Apartment 4a»,
Line2 = «123 West Street»,
City = «Northtown»,
State = «GA»,
Country = «USA»,
Zip = «12345»
};
// Arrange - create the test-specific email settings
EmailSettings settings = new EmailSettings {
// put test specific settings here
WriteAsFile = true
};
// Arrange - create the EmailOrderProcessor class
EmailOrderProcessor proc = new EmailOrderProcessor(settings);
// Act - process the order
proc. ProcessOrder (cart, shipDetails);
// NOTE - there is assert in this test
}
}
}
using SportsStore. WebUI. Controllers;
using Microsoft. VisualStudio. TestTools. UnitTesting;
using System;
using Microsoft. VisualStudio. TestTools. UnitTesting. Web;
using SportsStore. Domain. Abstract;
using System. Web. Mvc;
using Moq;
using SportsStore. Domain. Entities;
using System. Linq;
using System. Collections. Generic;
namespace SportsStore. UnitTests {
[TestClass()]
public class NavControllerTest {
[TestMethod]
public void Indicates_Selected_Category() {
// Arrange
// - create the mock repository
Mock<IProductRepository> mock = new Mock<IProductRepository>();
mock. Setup (m => m. Products).Returns (new Product[] {
new Product {ProductID = 1, Name = «P1», Category = «Apples»},
new Product {ProductID = 4, Name = «P2», Category = «Oranges»},
}.AsQueryable());
// Arrange - create the controller
NavController target = new NavController (mock. Object);
// Arrange - define the category to selected
string categoryToSelect = «Apples»;
// Action
string result = target. Menu(categoryToSelect).ViewBag. SelectedCategory;
// Assert
Assert. AreEqual (categoryToSelect, result);
}
[TestMethod]
public void MenuTest() {
// Arrange
// - create the mock repository
Mock<IProductRepository> mock = new Mock<IProductRepository>();
mock. Setup (m => m. Products).Returns (new Product[] {
new Product {ProductID = 1, Name = «P1», Category = «Apples»},
new Product {ProductID = 2, Name = «P2», Category = «Apples»},
new Product {ProductID = 3, Name = «P3», Category = «Plums»},
new Product {ProductID = 4, Name = «P4», Category = «Oranges»},
}.AsQueryable());
// Arrange - create the controller
NavController target = new NavController (mock. Object);
// Act = get the set of categories
string[] results = ((IEnumerable<string>) target. Menu().Model).ToArray();
// Assert
Assert. AreEqual (results. Length, 3);
Assert. AreEqual (results[0], «Apples»);
Assert. AreEqual (results[1], «Oranges»);
Assert. AreEqual (results[2], «Plums»);
}
}
}
using System;
using System. Web. Mvc;
using Microsoft. VisualStudio. TestTools. UnitTesting;
using SportsStore. WebUI. HtmlHelpers;
using SportsStore. WebUI. Models;
namespace SportsStore. UnitTests {
[TestClass()]
public class PagingHelpersTest {
[TestMethod]
public void Can_Generate_Page_Links() {
// Arrange - define an HTML helper - we need to do this
// in order to apply the extension method
HtmlHelper myHelper = null;
// Arrange - create PagingInfo data
PagingInfo pagingInfo = new PagingInfo {
CurrentPage = 2,
TotalItems = 28,
ItemsPerPage = 10
};
// Arrange - set up the delelgate using a lambda expression
Func<int, string> pageUrlDelegate = i => «Page» + i;
// Act
MvcHtmlString result = myHelper. PageLinks (pagingInfo, pageUrlDelegate);
// Assert
Assert. AreEqual (result. ToString(), @ "<a href=»«Page1» ">1</a><a class=»«selected»» href=» «Page2»">2</a><a href=» «Page3»">3</a>»);
}
}
}
using System. Collections. Generic;
using System. Linq;
using System. Web. Mvc;
using Microsoft. VisualStudio. TestTools. UnitTesting;
using Moq;
using SportsStore. Domain. Abstract;
using SportsStore. Domain. Entities;
using SportsStore. WebUI. Controllers;
using SportsStore. WebUI. Models;
using System;
using Microsoft. VisualStudio. TestTools. UnitTesting. Web;
namespace SportsStore. UnitTests {
[TestClass()]
public class ProductControllerTest {
[TestMethod]
public void Generate_Category_Specific_Product_Count() {
// Arrange
// - create the mock repository
Mock<IProductRepository> mock = new Mock<IProductRepository>();
mock. Setup (m => m. Products).Returns (new Product[] {
new Product {ProductID = 1, Name = «P1», Category = «Cat1»},
new Product {ProductID = 2, Name = «P2», Category = «Cat2»},
new Product {ProductID = 3, Name = «P3», Category = «Cat1»},
new Product {ProductID = 4, Name = «P4», Category = «Cat2»},
new Product {ProductID = 5, Name = «P5», Category = «Cat3»}
}.AsQueryable());
// Arrange - create a controller and make the page size 3 items
ProductController target = new ProductController (mock. Object);
target. PageSize = 3;
// Action - test the product counts for different categories
int res1 = ((ProductsListViewModel) target. List («Cat1»).Model).PagingInfo. TotalItems;
int res2 = ((ProductsListViewModel) target. List («Cat2»).Model).PagingInfo. TotalItems;
int res3 = ((ProductsListViewModel) target. List («Cat3»).Model).PagingInfo. TotalItems;
int resAll = ((ProductsListViewModel) target. List(null).Model).PagingInfo. TotalItems;
// Assert
Assert. AreEqual (res1, 2);
Assert. AreEqual (res2, 2);
Assert. AreEqual (res3, 1);
Assert. AreEqual (resAll, 5);
}
[TestMethod]
public void Can_Filter_Products() {
// Arrange
// - create the mock repository
Mock<IProductRepository> mock = new Mock<IProductRepository>();
mock. Setup (m => m. Products).Returns (new Product[] {
new Product {ProductID = 1, Name = «P1», Category = «Cat1»},
new Product {ProductID = 2, Name = «P2», Category = «Cat2»},
new Product {ProductID = 3, Name = «P3», Category = «Cat1»},
new Product {ProductID = 4, Name = «P4», Category = «Cat2»},
new Product {ProductID = 5, Name = «P5», Category = «Cat3»}
}.AsQueryable());
// Arrange - create a controller and make the page size 3 items
ProductController controller = new ProductController (mock. Object);
controller. PageSize = 3;
// Action
Product[] result = ((ProductsListViewModel) controller. List («Cat2», 1).Model)
Products. ToArray();
// Assert
Assert. AreEqual (result. Length, 2);
Assert. IsTrue (result[0].Name == «P2» && result[0].Category == «Cat2»);
Assert. IsTrue (result[1].Name == «P4» && result[1].Category == «Cat2»);
}
[TestMethod]
public void Can_Get_All_Products() {
// Arrange
// - create the mock repository
Mock<IProductRepository> mock = new Mock<IProductRepository>();
mock. Setup (m => m. Products).Returns (new Product[] {
new Product {ProductID = 1, Name = «P1», Category = «Cat1»},
new Product {ProductID = 2, Name = «P2», Category = «Cat2»},
new Product {ProductID = 3, Name = «P3», Category = «Cat1»},
new Product {ProductID = 4, Name = «P4», Category = «Cat2»},
new Product {ProductID = 5, Name = «P5», Category = «Cat3»}
}.AsQueryable());
// Arrange - create a controller and make the page size 3 items
ProductController controller = new ProductController (mock. Object);
controller. PageSize = 10;
// Action
Product[] result = ((ProductsListViewModel) controller. List (null, 1).Model)
Products. ToArray();
// Assert
Assert. AreEqual (result. Length, 5);
Assert. IsTrue (result[0].Name == «P1» && result[0].Category == «Cat1»);
Assert. IsTrue (result[1].Name == «P2» && result[1].Category == «Cat2»);
Assert. IsTrue (result[2].Name == «P3» && result[2].Category == «Cat1»);
Assert. IsTrue (result[3].Name == «P4» && result[3].Category == «Cat2»);
Assert. IsTrue (result[4].Name == «P5» && result[4].Category == «Cat3»);
}
[TestMethod]
public void Can_Send_Pagination_View_Model() {
// Arrange
// - create the mock repository
Mock<IProductRepository> mock = new Mock<IProductRepository>();
mock. Setup (m => m. Products).Returns (new Product[] {
new Product {ProductID = 1, Name = «P1»},
new Product {ProductID = 2, Name = «P2»},
new Product {ProductID = 3, Name = «P3»},
new Product {ProductID = 4, Name = «P4»},
new Product {ProductID = 5, Name = «P5»}
}.AsQueryable());
// Arrange - create a controller and make the page size 3 items
ProductController controller = new ProductController (mock. Object);
controller. PageSize = 3;
// Action
ProductsListViewModel result = (ProductsListViewModel) controller. List (null, 2).Model;
// Assert
PagingInfo pageInfo = result. PagingInfo;
Assert. AreEqual (pageInfo. CurrentPage, 2);
Assert. AreEqual (pageInfo. ItemsPerPage, 3);
Assert. AreEqual (pageInfo. TotalItems, 5);
Assert. AreEqual (pageInfo. TotalPages, 2);
}
[TestMethod]
public void Can_Paginate() {
// Arrange
// - create the mock repository
Mock<IProductRepository> mock = new Mock<IProductRepository>();
mock. Setup (m => m. Products).Returns (new Product[] {
new Product {ProductID = 1, Name = «P1»},
new Product {ProductID = 2, Name = «P2»},
new Product {ProductID = 3, Name = «P3»},
new Product {ProductID = 4, Name = «P4»},
new Product {ProductID = 5, Name = «P5»}
}.AsQueryable());
// create a controller and make the page size 3 items
ProductController controller = new ProductController (mock. Object);
controller. PageSize = 3;
// Action
ProductsListViewModel result = (ProductsListViewModel) controller. List (null, 2).Model;
// Assert
Product[] prodArray = result. Products. ToArray();
Assert. IsTrue (prodArray. Length == 2);
Assert. AreEqual (prodArray[0].Name, «P4»);
Assert. AreEqual (prodArray[1].Name, «P5»);
}
[TestMethod]
public void Can_Retrieve_Image_Data() {
// Arrange - create a Product with image data
Product prod = new Product {
ProductID = 2,
Name = «Test»,
ImageData = new byte[] {},
ImageMimeType = «image/png»};
// Arrange - create the mock repository
Mock<IProductRepository> mock = new Mock<IProductRepository>();
mock. Setup (m => m. Products).Returns (new Product[] {
new Product {ProductID = 1, Name = «P1»},
prod,
new Product {ProductID = 3, Name = «P3»}
}.AsQueryable());
// Arrange - create the controller
ProductController target = new ProductController (mock. Object);
// Act - call the GetImage action method
ActionResult result = target. GetImage(2);
// Assert
Assert. IsNotNull(result);
Assert. IsInstanceOfType (result, typeof(FileResult));
Assert. AreEqual (prod. ImageMimeType, ((FileResult) result).ContentType);
}
[TestMethod]
public void Cannot_Retrieve_Image_Data_For_Invalid_ID() {
// Arrange - create the mock repository
Mock<IProductRepository> mock = new Mock<IProductRepository>();
mock. Setup (m => m. Products).Returns (new Product[] {
new Product {ProductID = 1, Name = «P1»},
new Product {ProductID = 2, Name = «P2»}
}.AsQueryable());
// Arrange - create the controller
ProductController target = new ProductController (mock. Object);
// Act - call the GetImage action method
ActionResult result = target. GetImage(100);
// Assert
Assert. IsNull(result);
}
}
}
Размещено на Allbest.ru
Подобные документы
Разработка интернет-магазина, который специализируется на продаже книг. Сравнение технологий и средств разработки: языки программирования и программное обеспечение. Социальные сети и система управления контентом. Проектирование модели базы данных.
курсовая работа [3,6 M], добавлен 25.06.2012Принципы построения СУБД, их достоинства. Архитектура распределенной информационной системы. Разработка интернет-магазина рынка книг: построение физической модели данных на языке SQL, проектирование схемы базы данных с использованием веб-интерфейса.
курсовая работа [2,3 M], добавлен 01.11.2011Разработка интернет-магазина для реального заказчика. Проведение анализа и выбор интернет-технологий для разработки интернет-магазина. Проектирование предметной области. Разработка динамических web-страниц интернет-магазина, управляемых базой данных.
дипломная работа [1,7 M], добавлен 08.06.2013Проектирование книжного интернет-магазина для реализации книжной продукции через Интернет. Анализ и обоснование выбора языков программирования и средств разработки сайта. Затраты внедрение сайта, его программное обеспечение, тестирование и отладка.
дипломная работа [2,1 M], добавлен 06.06.2013Разработка тематических "онлайн-магазинов". Обоснование выбора информационных технологий. Архитектурное решение проекта. Разработка модели базы данных магазина. Схема базы данных на языке SQL. Интернет-магазины "ebay.com", "onliner.by", "eda.by".
курсовая работа [1,1 M], добавлен 24.06.2013Характеристика основных программных средств построения электронного магазина. Разработка структуры построения электронного магазина. Безопасность платежей в Интернете. Разработка алгоритма работы интернет-магазина. Разработка системы оплаты и доставки.
дипломная работа [1,9 M], добавлен 10.03.2014Обзор принципов построения информационных систем для торговли через интернет. Сравнительная характеристика программных средств построения электронного магазина. Проектирование и программная реализация интернет–магазина. Экономическое обоснование проекта.
дипломная работа [2,5 M], добавлен 13.02.2006Анализ объектно-ориентированной технологии программирования на примере языка Java. Методы, инструменты разработки web-приложений. Применение их при создании Интернет-магазина для ООО "Компас". Разработка апплета для его страницы в виде стрелочных часов.
курсовая работа [2,7 M], добавлен 31.01.2014Знакомство с организационно-функциональной структурой и хозяйственной деятельностью предприятия. Сравнительный анализ интернет-магазинов. Формирование требований к интернет-магазину. Обоснование экономической эффективности разработки интернет-магазина.
курсовая работа [1,4 M], добавлен 15.04.2012Проектирование даталогической модели в виде логической структуры реляционной базы данных в СУБД Microsoft SQL Server на основе созданной инфологической модели базы данных интернет-магазина музыки. Выделение сущностей и связей, анализ предметной области.
курсовая работа [724,6 K], добавлен 15.06.2013