29.05.2015 Views

o_19mgorv9t13a3ko71fev19l81mqa.pdf

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

[TestMethod]<br />

public void Can_Checkout_And_Submit_Order() {<br />

// Arrange - create a mock order processor<br />

Mock mock = new Mock();<br />

// Arrange - create a cart with an item<br />

Cart cart = new Cart();<br />

cart.AddItem(new Product(), 1);<br />

// Arrange - create an instance of the controller<br />

CartController target = new CartController(null, mock.Object);<br />

// Act - try to checkout<br />

ViewResult result = target.Checkout(cart, new ShippingDetails());<br />

// Assert - check that the order has been passed on to the processor<br />

mock.Verify(m => m.ProcessOrder(It.IsAny(),<br />

It.IsAny()),<br />

Times.Once());<br />

// Assert - check that the method is returning the Completed view<br />

Assert.AreEqual("Completed", result.ViewName);<br />

// Assert - check that I am passing a valid model to the view<br />

Assert.AreEqual(true, result.ViewData.ModelState.IsValid);<br />

}<br />

. . .<br />

Notice that I did not need to test that I can identify valid shipping details. This is handled for me automatically by the model<br />

binder using the attributes applied to the properties of the ShippingDetails class.<br />

Displaying Validation Errors<br />

The MVC Framework will use the validation attributes applied to the ShippingDetails class to validate user data.<br />

However, I need to make a couple of changes to display any problems to the user. The first issue is that I need to provide a<br />

summary of any problems to the user. This is especially important when dealing with problems that are not related to specific<br />

fields, such as when the user tries to check out with no items in the cart.<br />

To display a useful summary of the validation errors, I can use the Html.ValidationSummary helper method, just<br />

as I did in Chapter 2. Listing 9-19 shows the addition to Checkout.cshtml view.<br />

Listing 9-19. Adding a Validation Summary to the Checkout.cshtml File<br />

. . .<br />

@using (Html.BeginForm()) {<br />

@Html.ValidationSummary()<br />

Ship to<br />

<br />

Name<br />

@Html.TextBoxFor(x => x.Name, new {@class = "form-control"})<br />

<br />

Address<br />

. . .<br />

The next step is to create some CSS styles that target the classes used by the validation summary and those to which the MVC<br />

Framework adds invalid elements. I created a new Style Sheet called ErrorStyles.css in the Content folder<br />

251

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!