Unit Testing ASP.Net: Part 7, Testing Http Status Codes

This is Part 7 in a series on unit testing MVC. Part 1 and an index to all posts in this series is here.

In Part 6 if this series, I showed you how to handle two return types from the same method. I’ll continue that line with another method that returns multiple values. Here’ is the Delete method from the CustomerController.

   1:  public ActionResult Delete(int id = 0)
   2:  {
   3:      Customer customer = 
   4:          customerRepository.Customers.FirstOrDefault(c => c.Id == id);
   5:      if (customer == null)
   6:      {
   7:          return HttpNotFound();
   8:      }
   9:      return View(customer);
  10:  }

 

You know how to handle the return View(customer), but what about HttpNotFound()? This return error causes the browser to display a 404 error. While it may be better to display an appropriate message, this is how the default scaffolding code is generated and there may be times you want to cause a 404. So, let’s see how to handle this in a unit test.

   1:  [Test]
   2:  public void Delete_Invalid_Customer_Returns_Http_404()
   3:  {
   4:      // Arrange
   5:      Mock<ICustomerRepository> mock = new Mock<ICustomerRepository>();
   6:      Mock<IStateRepository> stateMock = new Mock<IStateRepository>();
   7:   
   8:      CustomerController controller = new CustomerController(mock.Object, 
   9:  stateMock.Object);
  10:      CustomerCreateEditViewModel viewModel = 
  11:  new CustomerCreateEditViewModel();
  12:              
  13:      // Act
  14:      var actual = controller.Delete(27) as HttpNotFoundResult;
  15:   
  16:      // Assert
  17:      Assert.AreEqual(404, actual.StatusCode);
  18:  }
 
 

Line 14 casts the return value to HttpNotFoundResult then in line 17 you Assert that the StatusCode value is 404. That’s it.

At this point, you should be able to write unit tests for all the methods in all three controllers in our example. But just as you get it done, you get a new requirement to add the country to the Customer Create and Edit pages. The user will first pick a country then the State/Province drop down will populate for the select country. This means you need to add a unit test to accept the Ajax call and test for a JSON response. I’ll show you how that’s done in Part 8.


ASP.Net MVC Unit Testing: Part 6, The [HttpPost] Method

This is Part 6 in a series on unit testing MVC. Part 1 and an index to all posts in this series is here.

In the previous post in this series, I showed you how to get test SelectList objects. We replaced the model with a viewmodel and passed that to the View. However, we didn’t deal with actually saving the data. I also detoured from unit testing a bit to show an easy way to map a model to a view model. Now it’s time to get back to our topic and learn how to test is a method that has multiple return points. In our sample application, we’re going to test the [HttpPost] Create method.

   1:  [HttpPost]
   2:  [ValidateAntiForgeryToken]
   3:  public ActionResult Create(CustomerCreateEditViewModel viewModel)
   4:  {
   5:      if (ModelState.IsValid)
   6:      {
   7:          Customer customer = AutoMapper.Mapper.Map<CustomerCreateEditViewModel,
   8:  Customer>(viewModel);
   9:          customer = customerRepository.Save(customer);
  10:          return RedirectToAction("Index");
  11:      }
  12:  
  13:      return View(viewModel);
  14:  }

Let’s deal with the first return on line 10. In order to get to that return, ModelState.IsValid must be ture. But how do we ensure this? We’ll need to add some validation to the ViewModel. To keep it simple, I’ll just require a FirstName and LastName. Here’s the changed code snippet.

   1:  [Required]
   2:  [DisplayName("First name")]
   3:  public string FirstName { get; set; }
   4:  
   5:  [Required]
   6:  [DisplayName("Last name")]
   7:  public string LastName { get; set; }

 

Now we need to write a test. In an earlier post in this series, I changed the return value of the controller method from ActionResult to ViewResult. We can’t do that here because if the ViewState is Valid, it returns a RedirectToAction, not a View. So, we need to ensure that we’re getting a RedirectToAction. That’s our first test.

   1:  [Test]
   2:  public void Create_ViewState_Is_Valid_Returns_RedirectToRouteResult()
   3:  {
   4:      // Arrange
   5:      Mock<ICustomerRepository> mock = new Mock<ICustomerRepository>();
   6:      Mock<IStateRepository> stateMock = new Mock<IStateRepository>();
   7:  
   8:      CustomerController controller = new CustomerController(mock.Object,
   9:  stateMock.Object);
  10:      CustomerCreateEditViewModel viewModel =
  11:  new CustomerCreateEditViewModel();
  12:      viewModel.FirstName = "Fred";
  13:      viewModel.LastName = "Flintstone";
  14:      AutoMapper.Mapper.Reset();
  15:      AutoMapper.Mapper.CreateMap<CustomerCreateEditViewModel,
  16:  Customer>();
  17:  
  18:      // Act
  19:      var actual = controller.Create(viewModel);
  20:  
  21:      // Assert
  22:      Assert.IsInstanceOf<RedirectToRouteResult>(actual);
  23:  }

 

In lines 10-13 we setup the ViewModel so that it will be valid. Lines 14-16 setup the mapping needed so that AutoMapper will work. We then call the Create method of the controller and in line 19 assert the return value os of the proper type.

Next we need to verify that the route value that gets returned is correct. The Create method returns to the Index action so that’s what we need to test for.

   1:  [Test]
   2:  public void Create_ViewState_Is_Valid_Contains_Correct_Action()
   3:  {
   4:      // Arrange
   5:      Mock<ICustomerRepository> mock = new Mock<ICustomerRepository>();
   6:      Mock<IStateRepository> stateMock = new Mock<IStateRepository>();
   7:  
   8:      CustomerController controller = new CustomerController(mock.Object,
   9:  stateMock.Object);
  10:      CustomerCreateEditViewModel viewModel =
  11:  new CustomerCreateEditViewModel();
  12:      viewModel.FirstName = "Fred";
  13:      viewModel.LastName = "Flintstone";
  14:      AutoMapper.Mapper.Reset();
  15:      AutoMapper.Mapper.CreateMap<CustomerCreateEditViewModel,
  16:  Customer>();
  17:  
  18:      // Act
  19:      var actual = controller.Create(viewModel) as RedirectToRouteResult;
  20:  
  21:      // Assert
  22:      Assert.AreEqual("Index", actual.RouteValues["action"]);
  23:  }

 

This test is similar to the previous one except that we cast the return value to RedirectToRouteResult so that we can interrogate it further. Line 19 asserts that the action is Index. Once you get green on both tests, it’s time to handle the condition that the ViewState is false.

First, change the return statement of the [HttpPost] Create method so it contains the actual View we want. Otherwise, the ViewName property is empty.

   1:  return View("Create", viewModel);

 

For our tests, we can test two things. The first is that we get a ViewResult (which is the View).

   1:  [Test]
   2:  public void Create_ViewState_Is_Invalid_Returns_ViewResult()
   3:  {
   4:      // Arrange
   5:      Mock<ICustomerRepository> mock = new Mock<ICustomerRepository>();
   6:      Mock<IStateRepository> stateMock = new Mock<IStateRepository>();
   7:  
   8:      CustomerController controller = new CustomerController(mock.Object,
   9:  stateMock.Object);
  10:      CustomerCreateEditViewModel viewModel =
  11:  new CustomerCreateEditViewModel();
  12:      controller.ModelState.AddModelError("FirstName", "First name is required");
  13:  
  14:      // Act
  15:      var actual = controller.Create(viewModel) as ViewResult;
  16:  
  17:      // Assert
  18:      Assert.IsInstanceOf<ViewResult>(actual);
  19:  }

 

In line 12, we set an error condition on the ModelState so it won’t pass. The Assert in line 18 verifies we get a ViewResult.

Now for the second test, we need to make sure we get the Create View.

   1:  [Test]
   2:  public void Create_ViewState_Is_Invalid_Returns_Correct_View()
   3:  {
   4:      // Arrange
   5:      Mock<ICustomerRepository> mock = new Mock<ICustomerRepository>();
   6:      Mock<IStateRepository> stateMock = new Mock<IStateRepository>();
   7:  
   8:      CustomerController controller = new CustomerController(mock.Object,
   9:  stateMock.Object);
  10:      CustomerCreateEditViewModel viewModel =
  11:  new CustomerCreateEditViewModel();
  12:      controller.ModelState.AddModelError("FirstName", "First name is required");
  13:  
  14:      // Act
  15:      var actual = controller.Create(viewModel) as ViewResult;
  16:  
  17:      // Assert
  18:      Assert.AreEqual("Create", actual.ViewName);
  19:  }

Really, the only difference between these last two tests is the Assert.

That wraps up testing the Create method. It should be easy to write tests for the Edit methods as they are the same as Create. Now we turn our attention to the Delete method.

   1:  public ActionResult Delete(int id = 0)
   2:  {
   3:      Customer customer =
   4:          customerRepository.Customers.FirstOrDefault(c => c.Id == id);
   5:      if (customer == null)
   6:      {
   7:          return HttpNotFound();
   8:      }
   9:      return View(customer);
  10:  }

 

Note the if statement on lines 5-8. If the requested Customer row isn’t found, the method returns HttpNotFound which results in a 404 error page in the browser. How do we test for this? That, is the topic of the next part in this series.

1 Comment more...

Unit Testing ASP.Net MVC: Part 5, Handling the SelectList

This is Part 5 in a series on unit testing MVC. Part 1 and an index to all posts in this series is here

Now that we’ve seen how to use repositories, mocks, and dependency injection to get around database access in our tests, we need to extend this to deal with the SelectList in the controller. Here’s what it looks like in the Create method of the CustomerController.

   1:  public ViewResult Create()
   2:  {
   3:      ViewBag.StateCode = new SelectList(db.States.OrderBy(s => s.Name),
   4:  "Code", "Name");
   5:      ViewBag.SalutationId = new SelectList(db.Salutations.OrderBy(s => s.Name),
   6:  "Id", "Name");
   7:      return View();
   8:  }

 

You can see that the context is being called. Let’s work through the SelectList for States. I’ll leave Salutations for you to do on your own. Add a new interface named IStateRepository to the Model folder.

   1:  public interface IStateRepository
   2:  {
   3:      IQueryable<State> States { get; }
   4:      State Save(State state);
   5:      void Delete(State state);
   6:  }

Now add a new class named EFStateRepository.


   1:  public class EFStateRepository : IStateRepository
   2:  {
   3:      Context context = new Context();
   4:  
   5:      public IQueryable<State> States
   6:      { get { return context.States; } }
   7:  
   8:      public State Save(State state)
   9:      {
  10:          if (state.Id == 0)
  11:          {
  12:              context.States.Add(state);
  13:          }
  14:          else
  15:          {
  16:              context.Entry(state).State = EntityState.Modified;
  17:          }
  18:          context.SaveChanges();
  19:          return state;
  20:      }
  21:  
  22:      public void Delete(State state)
  23:      {
  24:          context.States.Remove(state);
  25:          context.SaveChanges();
  26:      }
  27:  }

Now we need to refactor the CustomerController to use the StateRepository. Don’t change all the methods at once. Good refactoring is done in small steps. Let’s only make the changes needed for the Create method, starting with the constructor.

   1:  private Context db = new Context();
   2:  private ICustomerRepository customerRepository;
   3:  private IStateRepository stateRepository;
   4:  
   5:  public CustomerController(ICustomerRepository customerRepo,
   6:  IStateRepository stateRepo)
   7:  {
   8:      customerRepository = customerRepo;
   9:      stateRepository = stateRepo;
  10:  }

 

Here’s the modified Create method

   1:  public ViewResult Create()
   2:  {
   3:      ViewBag.StateCode = new SelectList(stateRepository.States.OrderBy(s => s.Name),
   4:  "Code", "Name");
   5:      ViewBag.SalutationId = new SelectList(db.Salutations.OrderBy(s => s.Name),
   6:  "Id", "Name");
   7:      return View();
   8:  }

 

Now modify the NinjectControllerFactory.AddBindings method to inject the EFCustomerRepository if needed.

   1:  private void AddBindings()
   2:  {
   3:      ninjectKernel.Bind<ICustomerRepository>().To<EFCustomerRepository>();
   4:      ninjectKernel.Bind<IStateRepository>().To<EFStateRepository>();
   5:  }

If you try to compile now, you’ll get an error. The unit tests we’ve already written don’t pass in a mocked IStateRepository. Let’s go ahead and refactor the tests so we can compile. I’m only showing one modified test here. The changes to the rest are similar.

   1:  [Test]
   2:  public void Customer_Index_Returns_ViewResult()
   3:  {
   4:      // Arrange
   5:      Mock<ICustomerRepository> mock = new Mock<ICustomerRepository>();
   6:      Mock<IStateRepository> stateMock = new Mock<IStateRepository>();
   7:  
   8:      mock.Setup(m => m.Customers).Returns(new Customer[]
   9:          {
  10:              new Customer {Id = 1, FirstName = "Herman", LastName = "Munster"},
  11:              new Customer {Id = 2, FirstName = "Rocky", LastName = "Squirrel"},
  12:              new Customer {Id = 3, FirstName = "George", LastName = "Washington"}
  13:          }.AsQueryable());
  14:  
  15:      CustomerController controller = new CustomerController(mock.Object, stateMock.Object);
  16:  
  17:      // Act
  18:      var actual = controller.Index();
  19:  
  20:      // Assert
  21:      Assert.IsInstanceOf<ViewResult>(actual);
  22:  }

We should be able to compile and all the existing tests should be green. Next we need to add tests for the Create method. There are actually two Create methods, one when the create form is initially displayed and the other when you attempt to save. I’ll start with the first one.

But, we have a problem. You can’t actually test the SelectList is stored to the ViewBag. Or at least, I haven’t found a way and a question posted to Twitter about it seems to confirm it. The solution is to use a ViewModel and include the SelectList as one of the properties. If all the input fields in a form use fields in a model, then you can use the model directly. If you need to include items that aren’t in the model, then you use a ViewModel, which is exactly what it sounds like, a special model just for the view.

We could create a class as the ViewModel that as a best practice, a ViewModel should be as flat as possible. Let’s create the ViewModel. Copy the Customer.cs file in the Models folder, then paste it back in the same folder and rename the new file to CustomerCreateEditViewModel.cs. Modify this new class, change the class name and add the following line to the end. Then modify the Create.cshtml file in the Customer View folder. Change the first line so the model is the new CustomerCreateEditViewModel.

   1:  @model MVCUnitTesting.Models.CustomerCreateEditViewModel

 

Compile and test the code to make sure it works. You’ll need to navigate to Create Customer form. Now it’s time to actually change how the select list works. Add a line at the bottom of the CustomerCreateEditViewModel to hold the list of states for the pick list.

   1:  public IEnumerable<SelectListItem> StateCodeList { get; set; }

And then modify the Create method of the CustomerController

   1:  public ViewResult Create()
   2:  {
   3:      CustomerCreateEditViewModel viewModel = new CustomerCreateEditViewModel();
   4:      viewModel.StateCodeList = new SelectList(stateRepository.States.OrderBy(s => s.Name),
   5:   "Code", "Name").ToList();
   6:      ViewBag.SalutationId = new SelectList(db.Salutations.OrderBy(s => s.Name),
   7:   "Id", "Name")
   8:      return View(viewModel);
   9:  }

 

There are a few changes needed here. We’re now using a ViewModel, so we need to create that in line 3 then pass it to the View in the return statement in line 8. Also, we populate the SateCodeList in line 4, which wasn’t much of change. We just needed to save the SelectList to the ViewModel instead of the ViewBag.

One more change is required. The Create View still references the ViewBag to display the States. Again, edit the Create.cshtml file. Find the line that sets up the DropDownList for the States and change it to the following.

   1:   @Html.DropDownListFor(model => model.StateCode, Model.StateCodeList)

Again, compile and test the application. Navigate to the Customer Create form and make sure the States dropdown is populated.

Now we can finally get to the task at hand, writing a unit test to verify the state list is populated correctly.

   1:  [Test]
   2:  public void Customer_Create_StateSelectList_Contains_Correct_Item_Count()
   3:  {
   4:      // Arrange
   5:      Mock<ICustomerRepository> mock = new Mock<ICustomerRepository>();
   6:      Mock<IStateRepository> stateMock = new Mock<IStateRepository>();
   7:  
   8:      stateMock.Setup(m => m.States).Returns(new State[]
   9:          {
  10:              new State {Id = 1, Name = "Oregon", Code = "OR"},
  11:              new State {Id = 2, Name = "Maine", Code = "ME"}
  12:          }.AsQueryable());
  13:  
  14:      CustomerController controller = new CustomerController(mock.Object, stateMock.Object);
  15:  
  16:      // Act
  17:      var actual = ((CustomerCreateEditViewModel)controller.Create().Model).StateCodeList.Count();
  18:  
  19:      // Assert
  20:      Assert.AreEqual(2, actual);
  21:  }

 

Hopefully, your test comes out as green. I’m not going to show the code for testing the Salutation as it’s the same as we have for State. But we’re not done yet. While the code compiles, you’ll see a red squiggly under customer in the [HttpPost] Create method. We’ll need to change this to support the ViewModel. We’re going to detour away from unit testing long enough to see how to make the needed change.

   1:  [HttpPost]
   2:  [ValidateAntiForgeryToken]
   3:  public ActionResult Create(Customer customer)
   4:  {
   5:      if (ModelState.IsValid)
   6:      {
   7:          customer = customerRepository.Save(customer);
   8:          return RedirectToAction("Index");
   9:      }
  10:  
  11:      return View(customer);
  12:  }

 

First, we need to change the code to use the ViewModel. You may think that we just replace customer with the viewModel. If you do, you’d be wrong. Remember the customerRepository.Save method takes a customer as a parameter. So, we’ll have to somehow map the viewmodel to the model. We could write a lot of code to do this, but that’s a lot of work. Every time we make a change to the model or the viewmodel we also have to remember to update the mapping code. I’m going to show an easy way to do this with a free tool called AutoMapper.

AutoMapper can be used just about anytime you need to map one object to another. A full explanation of AutoMapper is beyond the scope of this post. After all, we’re here to do unit testing, not object mapping.

To install AutoMapper, right-click on the References node of the MVCUnitTesting project and select Manage NuGet Packages. Search Online for AutoMapper, then click Install.

5-28-2013 10-51-57 PM_thumb[1]

Now we need to define the map. The definition only needs to be made once per application. Edit the Global.asax file and update it as shown.

   1:  using MVCUnitTesting.Models;
   2:  
   3:  namespace MVCUnitTesting
   4:  {
   5:      public class MvcApplication : System.Web.HttpApplication
   6:      {
   7:          protected void Application_Start()
   8:          {
   9:              AreaRegistration.RegisterAllAreas();
  10:  
  11:              WebApiConfig.Register(GlobalConfiguration.Configuration);
  12:              FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
  13:              RouteConfig.RegisterRoutes(RouteTable.Routes);
  14:              BundleConfig.RegisterBundles(BundleTable.Bundles);
  15:              AuthConfig.RegisterAuth();
  16:  
  17:              ControllerBuilder.Current.SetControllerFactory(new
  18:  NinjectControllerFactory());
  19:  
  20:              CreateMaps();
  21:          }
  22:  
  23:          public void CreateMaps()
  24:          {
  25:              AutoMapper.Mapper.Reset();
  26:              AutoMapper.Mapper.CreateMap<CustomerCreateEditViewModel,
  27:  Customer>();
  28:              AutoMapper.Mapper.AssertConfigurationIsValid();
  29:          }
  30:      }
  31:  }

 

Line 1 adds the using statement so the models and viewmodels are available. Then beginning at line 23, the mappings are defined. First, resest AutoMapper to clear out any previous mappings. We then setup the mapping from CustomerCreateEditVIewModel to Customer. Line 28 is important because it validates that mapping can be done. I’ve seen times when the mapping is invalid and no exception is thrown. The mapping simply doesn’t happen. Adding this line validates the mapping is correct. Finally, in line 20, CreateMaps is called.

Now we can add the actual mapping call to the Create method.

   1:  [HttpPost]
   2:  [ValidateAntiForgeryToken]
   3:  public ActionResult Create(CustomerCreateEditViewModel viewModel)
   4:  {
   5:      if (ModelState.IsValid)
   6:      {
   7:          Customer customer = AutoMapper.Mapper.Map<CustomerCreateEditViewModel,
   8:  Customer>(viewModel);
   9:          customer = customerRepository.Save(customer);
  10:          return RedirectToAction("Index");
  11:      }
  12:  
  13:      return View(viewModel);
  14:  }

As usual, you need to compile and test the application to ensure you can actually save a new customer.  Now that we can actually save a new customer, it’s time to return to our topic of writing unit tests for this method. But you’ll have to wait until the next post in this series when I talk about how to handle multiple returns with seemingly different values.

1 Comment more...

Unit Testing ASP.Net MVC: Part 4, Dependency Injection

This is Part 4 in a series on unit testing MVC. Part 1 and an index to all posts in this series is here.

In my last post in this series, I introduced you to mocks and explained there are still issues going on, even though the tests pass and the code runs correctly. The issue I mentioned is that we need to remove the need for multiple constructors and we can see why by looking at the Create method.

   1:  public ActionResult Create()
   2:  {
   3:      ViewBag.StateCode = new SelectList(db.States.OrderBy(s => s.Name), "Code", "Name");
   4:      ViewBag.SalutationId = new SelectList(db.Salutations.OrderBy(s => s.Name), "Id", "Name");
   5:      return View();
   6:  }

 

Here we create two SelectLists to handle the DropDown boxes on the create form. Do you see a problem? The code calls into the database instead of using repositories. So, in order to unit test, we need to pass in mocked repositories. We can do this in a few different ways.

First, we can add two additional parameters to the second constructor so that we pass not only mocked repositories for the Customer, but also the State and Salutation. That means we have to mock those even if we don’t use them in the test. This is bad practice. The test should only create what it needs.

Second, we can add another constructor that passes all three mocked repositories. But this means as we add functionality, we may need to add more and more constructors just to test the code. I have production code with forms that have a dozen or more dropdowns. This gets very complicated and difficult to maintain. Again, a bad practice.

The real solution is to use dependency injection. Here’s the Wikipedia definition

Dependency injection is a software design pattern that allows removing hard-coded dependencies and making it possible to change them, whether at run-time or compile-time.

This can be used, for example, as a simple way to load plugins dynamically or to choose stubs or mock objects in test environments vs. real objects in production environments. This software design pattern injects the depended-on element (object or value etc) to the destination automatically by knowing the requirement of the destination.

So, what we’re going to do is add a dependency injection (DI) controller that will say, “If ICustomerRepository object is not passed into the class, then use the default. If one is passed in, use it.”

Once again, the first step is to use NuGet to get the DI controller installed into the solution. There are several DI controllers you can choose from. We’re going to use one called Ninject. The first step is to right-click on the References node of the MVCUnitTests project (this is our main project, not the one that has the actual unit tests) and select Manage NuGet Packages. Search online for Ninject and when found, click Install.

5-22-2013 10-02-08 PM

 

Notice in this dialog that Ninject is described as an “IoC container”. IoC stands for Inversion of Control, basically another name for Dependency Injection. Now we need to do just a little coding to make this work. To start, add a new class named NinjectControllerFactory.cs to the App_Start folder of the project.

   1:  using System;
   2:  using System.Web.Mvc;
   3:  using System.Web.Routing;
   4:  using MVCUnitTesting.Models;
   5:  using Ninject;
   6:   
   7:  namespace MVCUnitTesting.App_Start
   8:  {
   9:      public class NinjectControllerFactory : DefaultControllerFactory
  10:      {
  11:          private IKernel ninjectKernel;
  12:          
  13:          public NinjectControllerFactory()
  14:          {
  15:              ninjectKernel = new StandardKernel();
  16:              AddBindings();
  17:          }
  18:   
  19:          protected override IController 
  20:  GetControllerInstance(RequestContext requestContext, Type controllerType)
  21:          {
  22:              return controllerType == null ? null : 
  23:  (IController)ninjectKernel.Get(controllerType);
  24:          }
  25:   
  26:          private void AddBindings()
  27:          {
  28:              ninjectKernel.Bind<ICustomerRepository>().To<EFCustomerRepository>();
  29:          }
  30:      }
  31:  }
 
Everything in this class is required to setup Ninject.Note the AddBindings method on line 26 and the references to ICustomerRepository and EFCustomerRepository on line 28. It’s this line that tells Ninject to use EFCustomerRepository if an ICustomerRepository is not passed into the class. As you add other repositories to the application, you need to come back here and add bindings for them too.
Next we need to instantiate this new class. Open the Global.asax file and at the end of the Application_Start method, add this line.
   1:  ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());

 

Finally, we need to go back to the CustomerController and remove the default constructor. Remember, Ninject will handle injecting an EFCustomerRepository if we don’t pass in one that is mocked in the tests.

Your tests should still be green and if you run the application and navigate to the Customer Index, data should be pulled from the database. But we’re still not done. Remember the references to setup the SelectLists I mentioned at the beginning of this post? We need to add repositories for those tables and then tests for the remaining methods of the CustomerController. I’ll leave the States and Salutations tables for you. In the next post, I’ll begin to address the remaining CustomerController methods.


Unit Testing ASP.Net MVC: Part 3, Mocks

This is Part 3 in a series on unit testing MVC. Part 1 and an index to all posts in this series is here.

Welcome back to this journey of unit testing ASP.Net MVC. If you’re still with me, it means I didn’t bore you too much. In the previous installment, I introduced you to repositories and explained why they help remove dependencies on databases so you can do real unit testing. However, we haven’t completely removed this dependency yet. The tests will still call into the database. There are two things we need to do to remove this dependency, mocks and dependency injection. Today I will discuss mocks.

As you get into unit testing you learn about ways to trick the application into thinking it’s really connecting to outside objects, whether that be the file system, a database, or a web service. You do this through fakes, mocks, or stubs. Wikipedia describes these:

Some authors draw a distinction between fake and mock objects. Fakes are the simpler of the two, simply implementing the same interface as the object that they represent and returning pre-arranged responses. Thus a fake object merely provides a set of method stubs.

In the book "The Art of Unit Testing" mocks are described as a fake object that helps decide whether a test failed or passed by verifying whether an interaction with an object occurred. Everything else is defined as a stub. In that book, "Fakes" are anything that is not real. Based on their usage, they are either stubs or mocks.

Mock objects in this sense do a little more: their method implementations contain assertions of their own. This means that a true mock, in this sense, will examine the context of each call— perhaps checking the order in which its methods are called, perhaps performing tests on the data passed into the method calls as arguments.

I’m just going to use the generic term “mock” and not try to differentiate between a mock and a fake for one reason…I don’t want to get caught up in terminology. My goal is to show you how to unit test MVC. Splitting hairs over a definition won’t get us to that goal.

The easiest way to use mocks is with a mocking framework. there are several available. We’ll use one called Moq and the easiest way to install Moq is with a NuGet package. Right click the References node on the UnitTests project and select “Manage NuGet Packages”. Search online for Moq. Once it’s found, click Install.

5-22-2013 8-46-31 PM

If you recall, from earlier posts, I mentioned there were two big problems with the test. The first is that we call into the database and the second that we can never guarantee the number of records in the database to be the same between each run. We’re going to simulate doing this. Let’s add a new test that makes sure we get three customers back as part of the return from the Index method.

   1:  [Test]
   2:  public void Customer_Index_Contains_3_Customers()
   3:  {
   4:      // Arrange
   5:      Mock<ICustomerRepository> mock = new Mock<ICustomerRepository>();
   6:      mock.Setup(m => m.Customers).Returns(new Customer[]
   7:          {
   8:              new Customer {Id = 1, FirstName = "Herman", LastName = "Munster"},
   9:              new Customer {Id = 2, FirstName = "Rocky", LastName = "Squirrel"},
  10:              new Customer {Id = 3, FirstName = "George", LastName = "Washington"}
  11:          }.AsQueryable());
  12:   
  13:      CustomerController controller = new CustomerController(mock.Object);
  14:   
  15:      // Act
  16:      var actual = (List<Customer>)controller.Index().Model;
  17:   
  18:      // Assert
  19:      Assert.AreEqual(3, actual.Count);
  20:  }

 

This code may seem quite strange if you’ve never used mocks. Line 5 sets up the mock of type ICustomerRepository. Lines 6-11 tell the mocking framework that when requested, it should return an array of three Customer objects of type Queryable. Then on line 13, we pass the mock object to the constructor of the CustomerController. If you try to compile the solution, you’ll get an error. The problem is, there is no constructor in the CustomerController. Let’s fix that.

   1:  public class CustomerController : Controller
   2:  {
   3:      private Context db = new Context();
   4:      private ICustomerRepository customerRepository;
   5:   
   6:      public CustomerController()
   7:      {
   8:          customerRepository = new EFCustomerRepository();
   9:      }
  10:   
  11:      public CustomerController(ICustomerRepository customerRepo)
  12:      {
  13:          customerRepository = customerRepo;
  14:      }

 

Note on line 4 that we don’t instantiate the CustomerRepository when we define it. We also needed to add a default constructor (lines 6-9) then the new constructor to handle the parameter instance of ICustomerRepository that we’re passing in. All three of our tests should be passing. However, two of them are still calling into the actual database. Let’s fix that.

 
   1:  [TestFixture]
   2:  public class CustomerUnitTests
   3:  {
   4:  [Test]
   5:  public void Customer_Index_Returns_ViewResult()
   6:  {
   7:      // Arrange
   8:      Mock<ICustomerRepository> mock = new Mock<ICustomerRepository>();
   9:      mock.Setup(m => m.Customers).Returns(new Customer[]
  10:          {
  11:              new Customer {Id = 1, FirstName = "Herman", LastName = "Munster"},
  12:              new Customer {Id = 2, FirstName = "Rocky", LastName = "Squirrel"},
  13:              new Customer {Id = 3, FirstName = "George", LastName = "Washington"}
  14:          }.AsQueryable());
  15:   
  16:      CustomerController controller = new CustomerController(mock.Object);
  17:   
  18:      // Act
  19:      var actual = controller.Index();
  20:   
  21:      // Assert
  22:      Assert.IsInstanceOf<ViewResult>(actual);
  23:  }
  24:   
  25:  [Test]
  26:  public void Customer_Index_View_Contains_ListOfCustomer_Model()
  27:  {
  28:      // Arrange
  29:      Mock<ICustomerRepository> mock = new Mock<ICustomerRepository>();
  30:      mock.Setup(m => m.Customers).Returns(new Customer[]
  31:          {
  32:              new Customer {Id = 1, FirstName = "Herman", LastName = "Munster"},
  33:              new Customer {Id = 2, FirstName = "Rocky", LastName = "Squirrel"},
  34:              new Customer {Id = 3, FirstName = "George", LastName = "Washington"}
  35:          }.AsQueryable());
  36:   
  37:      CustomerController controller = new CustomerController(mock.Object);
  38:   
  39:      // Act
  40:      var actual = (List<Customer>)controller.Index().Model;
  41:   
  42:      // Assert
  43:      Assert.IsInstanceOf<List<Customer>>(actual);
  44:  }

Just like that, we’re no longer calling into the database to test the Index method. This may seem like a lot of code just to test one simple method. But if you think about it, we need to test that the results are correct. The great thing is if we change the functionality of the Index method, it takes just a few seconds to make sure the code is correct.

There are more issues that we need to fix. You may not even see one of them because the code runs and all our tests pass. In my next post in this series, I’ll remove the need to have two constructors and explain why that’s important.

1 Comment more...

Unit Testing ASP.Net MVC: Part 2, Repositories

This is Part 2 in a series on unit testing MVC. Part 1 and an index to all posts in this series is here.

In the first part of this series, I introduced a simple ASP.Net MVC 4 application, created a test, and then showed several ways to run it. We also learned that because the test hit the database, it actually wasn’t a unit test, but rather an integration test. In Part 2, we’ll start working towards removing the need to hit the database.

In this post, I will introduce the repository pattern. It will seem like a lot of unnecessary work, but if you want the Controller to be testable, this step is important. According to MSDN, “The repository mediates between the data source layer and the business layers of the application. It queries the data source for the data, maps the data from the data source to a business entity, and persists changes in the business entity to the data source. A repository separates the business logic from the interactions with the underlying data source or Web service.”

Currently, data access goes from the Controller to the Context that directly calls Entity Framework (EF) to handle the data access.

5-19-2013 1-52-46 PM

Here’s the code for the Context. Note that Context is subclassed from DbContext, which is part of Entity Framework and doesn’t have an interface. This means we can’t just replace the Context with something else.

   1:  public class Context : DbContext
   2:  {
   3:      public DbSet<Customer> Customers { get; set; }
   4:      public DbSet<Salutation> Salutations { get; set; }
   5:      public DbSet<State> States { get; set; }
   6:  }

 

The change to the repository pattern changes data access to go from the Controller to the Repository, then to the Context and Entity Framework.

5-19-2013 1-53-31 PM

This may seem like a small change, but it reaps big benefits. The Repository is based on an interface, so we can easily replace it for our tests and never call the Context nor Entity Framework.

As a first step, let’s add an interface to the Models folder. Name it ICustomerRepository.

   1:  public interface ICustomerRepository
   2:  {
   3:      IQueryable<Customer> Customers { get; }
   4:      Customer Save(Customer customer);
   5:      void Delete(Customer customer);
   6:  }

 

Now we need to implement the interface. Create a new class named EFCustomerRepository in the Models folder.  

 1:  public class EFCustomerRepository : ICustomerRepository
 2:  {
 3:      Context context = new Context();
 4:
 5:      public IQueryable<Customer> Customers
 6:      { get { return context.Customers; } }
 7:
 8:      public Customer Save(Customer customer)
 9:      {
 10:          if (customer.Id == 0)
 11:          {
 12:              context.Customers.Add(customer);
 13:          }
 14:          else
 15:          {
 16:              context.Entry(customer).State = EntityState.Modified;
 17:          }
 18:          context.SaveChanges();
 19:          return customer;
 20:      }
 21:
 22:      public void Delete(Customer customer)
 23:      {
 24:          context.Customers.Remove(customer);
 25:          context.SaveChanges();
 26:       }
 27:  }

 

 

 

 

Now that we have defined the repository, we need to make use of it. We’ll change the CustomerController. Here’s the section we’re interested in.

   1:  public class CustomerController : Controller
   2:  {
   3:      private Context db = new Context();
   4:  
   5:      public ViewResult Index()
   6:      {
   7:          return View(db.Customers.ToList());
   8:      }

 

Since we only have tests for the Index method, we’ll only make the changes there, plus add a new field to handle the reference to the repository.

   1:  public class CustomerController : Controller
   2:  {
   3:      private Context db = new Context();
   4:      private ICustomerRepository customerRepository = new EFCustomerRepository();
   5:  
   6:      public ViewResult Index()
   7:      {
   8:          return View(customerRepository.Customers.ToList());
   9:      }

Compile the code and run the tests. (If you are using NCrunch, the tests will run automatically). You should get green for the Index method. This shows the benefits of unit testing. You can modify code and if the tests still pass, you have a high confidence that you didn’t change the functionality. We’ll also leave the instantiation of the Context for now since it’s still being used.

As you can guess, we’ll want to update the other Controller methods to use the repository. This brings up a dilemma. We can change the code, but we don’t have tests to run to verify the changes work. But, because we’re actually hitting the database, we can’t verify the tests right now will be accurate either. If we write the tests now, we’ll have to modify them later when we get to mocking the database, so I’ll opt to write the tests later, but I’ll change the Controller now to use the repository.

   1:  public class CustomerController : Controller
   2:  {
   3:  private Context db = new Context();
   4:  private ICustomerRepository customerRepository = new EFCustomerRepository();
   5:  
   6:  public ViewResult Index()
   7:  {
   8:      return View(customerRepository.Customers.ToList());
   9:  }
  10:  
  11:  public ActionResult Details(int id = 0)
  12:  {
  13:      Customer customer =
  14:          customerRepository.Customers.FirstOrDefault(c => c.Id == id);
  15:      if (customer == null)
  16:      {
  17:          return HttpNotFound();
  18:      }
  19:      return View(customer);
  20:  }
  21:  
  22:  public ActionResult Create()
  23:  {
  24:      ViewBag.StateCode = new SelectList(db.States.OrderBy(s => s.Name), "Code", "Name");
  25:      ViewBag.SalutationId = new SelectList(db.Salutations.OrderBy(s => s.Name), "Id", "Name");
  26:      return View();
  27:  }
  28:  
  29:  [HttpPost]
  30:  [ValidateAntiForgeryToken]
  31:  public ActionResult Create(Customer customer)
  32:  {
  33:      if (ModelState.IsValid)
  34:      {
  35:          customer = customerRepository.Save(customer);
  36:          return RedirectToAction("Index");
  37:      }
  38:  
  39:      return View(customer);
  40:  }
  41:  
  42:  public ActionResult Edit(int id = 0)
  43:  {
  44:      Customer customer =
  45:          customerRepository.Customers.FirstOrDefault(c => c.Id == id);
  46:      if (customer == null)
  47:      {
  48:          return HttpNotFound();
  49:      }
  50:      return View(customer);
  51:  }
  52:  
  53:  [HttpPost]
  54:  [ValidateAntiForgeryToken]
  55:  public ActionResult Edit(Customer customer)
  56:  {
  57:      if (ModelState.IsValid)
  58:      {
  59:          customerRepository.Save(customer);
  60:          return RedirectToAction("Index");
  61:      }
  62:      return View(customer);
  63:  }
  64:  
  65:  public ActionResult Delete(int id = 0)
  66:  {
  67:      Customer customer =
  68:          customerRepository.Customers.FirstOrDefault(c => c.Id == id);
  69:      if (customer == null)
  70:      {
  71:          return HttpNotFound();
  72:      }
  73:      return View(customer);
  74:  }
  75:  
  76:  [HttpPost, ActionName("Delete")]
  77:  [ValidateAntiForgeryToken]
  78:  public ActionResult DeleteConfirmed(int id)
  79:  {
  80:      Customer customer =
  81:          customerRepository.Customers.FirstOrDefault(c => c.Id == id);
  82:      customerRepository.Delete(customer);
  83:      return RedirectToAction("Index");
  84:  }

 

How do you test this code? You have to run the application, navigate to each page, and exercise it’s functionality, then examine the result. I can guarantee that will take longer than running unit tests. But, this Controller will be ready for when the tests call the methods without making calls to the database.

That’s it for Part 2. Coming up in Part 3, we’ll continue on the journey of removing the database from the tests by introducing Mocks.


Unit Testing ASP.Net MVC: Part 1, Getting Started

This is Part 1 in a series of posts.

ASP.Net MVC is designed for testability. Separating the Model, View, and Controller, makes it much easier to test your application. But, the standard MVC template doesn’t allow good unit testing right out of the box. You need to do some coding and add some additional assemblies to do good unit testing.

In this series, you will learn about problems with the default template and how to get around them.I’m not going to do TDD here because I feel you get a better understanding of the needed changes if we walk through changing the code to be more testable rather than jumping straight to TDD. Also, I think you get a better understanding of unit testing if you learn this way.5-18-2013 1-27-36 PM And you need a good understanding of unit testing to do TDD correctly.

To get started, we need an MVC application. I want to keep it simple so that it’s easier to understand what we’re doing. The example solution I am using is called MVCUnitTesting. You can download the Visual Studio solution if you want to follow along. I used the Internet MVC 4 application template. The application has one simple data entry form and CRUD forms for two supporting lookup tables. Note that when I created the application, I did not check “Create a Unit Test project” on the new project dialog. Here’s the Create Customer page from the application. We will write unit tests for the Customer Controller.

Now that we have our application, we need to assemble our unit test tools. Visual Studio ships with it’s own unit test framework and test runner. The problem with it is the test runner is part of Visual Studio and can’t be pulled out to run automated tests. This means if you aren’t using TFS for Continuous Integration, you need a different unit test framework. I prefer NUnit and will use it for this series.

Before installing NUnit, let’s create an empty project for our tests. Right-click on the solution in Solution Explorer and add a new class library project named UnitTests then delete the .cs file that was created. A good practice is to place unit tests into their own project. This is not something you will distribute with your application.

Now, expand the new UnitTests project node, right-click on References and select Manage NuGet Packages. In the search box, select NUnit, then click Install. This will install NUnit into the the UnitTests project. You will not install it into the MVC project.

5-18-2013 1-59-06 PM

You will also need to add a reference to the MVCUnitTesting project.

Now it’s time to write our first unit test, but where to start? The beginning is often a good place, so how about the CustomerController.Index method. Here it is:

   1:  public ActionResult Index()
   2:  {
   3:      return View(db.Customers.ToList());
   4:  }

 

I can see two things that you may want to test for. The first, is that the return value is of the expected type. In this case, it’s an ActionResult. The other thing I see is that the model is List<Customer>, so we can check that is correct. So, let’s start with the first thing and make sure we actually get back an ActionResult.

To add the unit test, right-click the UnitTests project and add a new class named CustomerUnitTests. First, add a [TestFixture] attribute to the class. If prompted to add a using statement, do so. Next, create the first method. Unit test methods are public void. By convention, the name of the method tells you what you are testing, so name the method Customer_Index_Returns_ActionResult. You will also need to add a [Test] attribute to the method. As you add the code, Visual Studio may indicate you are missing some references or using statements. Add the ones you’re missing. Here’s the first attempt at writing this test.

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using System.Text;
   5:  using System.Threading.Tasks;
   6:  using System.Web.Mvc;
   7:  using NUnit.Framework;
   8:  using MVCUnitTesting.Controllers;
   9:  using MVCUnitTesting.Models;
  10:  
  11:  namespace UnitTests
  12:  {
  13:      [TestFixture]
  14:      public class CustomerUnitTests
  15:      {
  16:          [Test]
  17:          public void Customer_Index_Returns_ActionResult()
  18:          {
  19:              // Arrange
  20:              CustomerController controller = new CustomerController();
  21:  
  22:              // Act
  23:              var actual = controller.Index();
  24:  
  25:              // Assert
  26:              Assert.IsInstanceOf<ActionResult>(actual);
  27:          }
  28:      }
  29:  }

 

There are several things to note about this code. First, the method has three parts, Arrange, Act, Assert. This is another good practice. In Arrange, you set everything up to run the test. This includes things like getting a reference to the class, creating any values that may need to be passed to the method, etc. Act is where you actually call the method you are tested. Assert is where you validate that the method returned the value you expected.

But there are some issues with the method.  For example, you can’t instantiate a new ActionResult. This is because ActionResult is an abstract class and as it turns out, is the parent class for several other data types. Hmmm..looking at the actual return statement of the Index method, we see that it returns a View. That means, View is a subclass of ActionResult. Rather than go through several steps trying to get this to work, I’ll cut to the chase. You need to return a different data type, not something abstract. It needs to be something concrete.

And this is one thing that makes unit testing MVC applications so difficult. Knowing what things are and how to change what gets returned to something you can test for. This takes learning about MVC. And this brings up another good practice, which is, return the most specific data type you can.

In our case, we’re going to return a ViewResult. Here’s the new Index method.

   1:  public ViewResult Index()
   2:  {
   3:      return View(db.Customers.ToList());
   4:  }

 

And now the updated test method. Don’t forget to change the name of this method as we will now expect a ViewResult, not an ActionResult.

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using System.Text;
   5:  using System.Threading.Tasks;
   6:  using System.Web.Mvc;
   7:  using NUnit.Framework;
   8:  using MVCUnitTesting.Controllers;
   9:  
  10:  namespace UnitTests
  11:  {
  12:      [TestFixture]
  13:      public class CustomerUnitTests
  14:      {
  15:          [Test]
  16:          public void Customer_Index_Returns_ViewResult()
  17:          {
  18:              // Arrange
  19:              CustomerController controller = new CustomerController();
  20:  
  21:              // Act
  22:              var actual = controller.Index();
  23:  
  24:              // Assert
  25:              Assert.IsInstanceOf<ViewResult>(actual);
  26:          }
  27:      }
  28:  }

 

Now that you have the unit test written and you can compile, it’s time to run the test. Unit tests use the terms red and green for fail and pass, so we want our test to be green. There are actually a number of ways to run this test. Let’s start with the NUnit runner.

To get the NUnit runner, go to www.nunit.org and download and install NUnit. Once you’ve done that, launch NUnit.exe. Next you need to setup your test. NUnit does this via NUnit projects. From the NUnit menu, select File –> New Project. I named mine MVCUnitTesting and saved it to the same folder as my MVCUnitTesting Visual Studio solution. This will create a file names MVCUnitTesting.nunit.

Next you need to tell NUnit which assembly to use. Select Project –> Add Assembly and select UnitTests.dll from the bin folder. When that’s done, click Run. If all goes well, you’ll get a green bar.

5-18-2013 3-53-48 PM

NUnit also ships with a console application runner for use with Continuous Integration servers.

Running unit tests this way is easy and inexpensive, but you have to step outside Visual Studio. There is documentation on the NUnit site on how to call NUnit from inside Visual Studio, but truthfully, it’s an older, outdated method.

This next method only works with Visual Studio 2012 (and even then, not with the Express edition). Beginning with VS2012, Microsoft opened up the built-in test runner to provide support for third-party test tools. First you have to download NUnit Test Adapter. To do this, select Tools –> Extensions and Updates from the Visual Studio menu. Make sure Online is selected on the left-hand side. Enter NUnit Test Adapter into the search dialog then click Download. You will be prompted to install and then you’ll need to restart Visual Studio.

Once Visual Studio restarts, you should see the Test Explorer window. If not, select Test –> Windows –> Test Explorer on the Visual Studio menu. In the Test Explorer window, click Run.

5-18-2013 4-08-16 PM

These first two ways to run tests are free. Now let’s look at some pay-for test runners. The first is Resharper available at www.jetbrains.com. This is a great tool and if you don’t have it, I highly recommend that you purchase it as it will totally change the way you write code. Resharper has adidtional keyboard shortcuts, refactorings, autocode insertion, and many other productivity enhancements. It also includes a test runner that works with NUnit.

To run a test from Resharper, first position your cursor on the test you want to run, then select Resharper –> Unit Tests –> Run Unit Tests from the Visual Studio menu.

5-18-2013 4-12-26 PM

The other way to have Resharper run tests is to select Resharper –> Unit Tests –> Run All Unit Tests from Solution. This will run all the tests in the solution and the cursor can be positioned anywhere in the solution.

The last way I’m going to show you how to run unit tests is also a paid add-on. But I think this really is by far the best way to run unit tests. It’s a fairly new product called NCrunch. You download it here. Why is NCrunch superior? First, it automatically runs unit tests. No muss, no fuss. It keeps track of your code and tests as you edit them, recompiles in the background, and then runs the tests in the background. You get immediate feedback on which tests are failing and passing right in the Visual Studio editor.

Additionally, NCrunch automatically shows Code Coverage. This means you know which lines of code are covered by a unit test and which aren’t. It does this by adding a red dot in the VS editor for each line that fails, a green dot if it passes, and a black dot if the line is not under test.

Once you’ve downloaded and installed NCrunch, you need to enable it for the project. From the Visual Studio menu, select NCrunch –> Enable NCrunch. You’ll then need to walk through a series of choices. As you get started with unit tests, here’s how I think you should select options.

The first page is Parallel Execution. Select the default and click Next

On the second page, Engine Execution Mode, again select the default and click Next.

The third page is Ignored Tests. Select the option Let my tests run then click Next. Click Finish and you’re done. This will cause the tests to be run automatically.

Once you’re done with the setup, the tests should run automatically and the results show up inside the Visual Studio editor. Here are the screen captures of the Index method and the test.

5-18-2013 4-37-18 PM

5-18-2013 4-47-52 PM

Notice that some of the lines have a yellow dot with a green border. This is what NCrunch calls a hot spot. It’s defined as a line of code that runs slowly. I’ll come back to these lines in a bit. First, let’s handle the second test I suggested, that the model attached to the view be List<Customer>. Here’s the new test.

   1:  [Test]
   2:  public void Customer_Index_View_Contains_ListOfCustomer_Model()
   3:  {
   4:      // Arrange
   5:      CustomerController controller = new CustomerController();
   6:  
   7:      // Act
   8:      var actual = (List<Customer>)controller.Index().Model;
   9:  
  10:      // Assert
  11:      Assert.IsInstanceOf<List<Customer>>(actual);
  12:  }

 

One of the great things about NCrunch is the test is run as soon as you write it. You get immediate feedback. I think this not only makes you more productive, but helps you learn unit testing faster.

Looking at the Controller code, you see that the Model is a List<Customer> and every Customer record in the database should be included. How do we know the List contains all the rows in the Customer table? This is difficult to test as that can change in the database.

Remember the yellow dots with green borders? The code is slow because it actually hits the database. This not only means that the tests are slow, but additional tests could return invalid results as the data changes. It also means THIS IS NOT A UNIT TEST! It is an integration test. Unit tests do not hit the database or external components.

And that’s where I’ll go in Part 2 of this series. We’ll begin to refactor the code so we can avoid the database when running unit tests. It will take a few steps to get there, but I’ll take you along slowly.

Index to posts in this series

Part 1: Getting Started

Part 2: Repositories

Part 3: Mocks

Part 4: Dependency Injection

Part 5: Handling the SelectList

Part 6: The [HttpPost] Method

Part 7: Testing Http Status Codes


OpenWest Conference

For the past several years, the Utah Open Source community has come together for the Utah Open Source Conference. This year, it has a different name as it grows and works to become a regional conference. Welcome to OpenWest Conference! This year, OpenWest is being held on the campus of Utah Valley University in Orem. It’s going on now through Saturday. In three days of great content you’ll hear about all sorts of Open Source goodness.

I will be speaking there too. My session, “Ooey GUI Web” is set for 11:00  11:00, in room SB276. This session will cover several Open Source web UI widgets including JQueryUI, Wijmo Open (the Open Source version of Component One‘s great Wijmo line), and JQuery DataTables. Come and find out how easy it is to add these great widgets to your web pages.


Boise Code Camp 2013

The vendor area contained several tables from companies trying to reWP_20130316_002cruit or sell their products. To encourage you to visit the vendors, each attendee got a “bingo” card. At each vendor table, you got a sticker put in designated square on the bingo card. You then had to write your name on the card and drop it in a box to be entered into a drawing for a Star Wars Xbox. The drawing would be held at the end of the day.

Each attendee also got one raffle ticket to drop in the box for the prize of your choice. Various component vendors had donated prizes as well as copy of Windows 8 Pro and a one year subscription to Pluralsight. These drawings were also made at the end of day.

My trip started Friday with a drive to Boise from Salt Lake City. Less than five hours later, I was checked into my hotel across the street from BSU. I wasn’t there long. The speaker dinner was scheduled for the evening at Fuddruckers. It was good to see old friends and meet new people. After downing a burger, it was time to stuff the attendee bags. Then, it was back to the hotel. A good sleep the night before a presentation helps make it better.WP_20130316_001

Saturday morning kicked off with breakfast and an opening session where we were welcomed and last minute announcements made. The schedule had 10 simultaneous 75-minute sessions across five time slots. I checked in, got my attendee bag, then headed for the green room. Just outside the speaker room, I saw a sign directing people to a prayer meeting. Somehow, it seemed appropriate. Inside, the speaker room was stocked with snacks, water, and even antacid.

I opted for “Designing Web Applications” presented by Nathan Barry. He pointed out that a web application is different than a web site. A web site is something you visit once in a while. A web application is something you use day-in and day-out to do your job. You may WP_20130316_005-aspend most of you day working in it. It’s more important that a web application be rock solid because if not, it will affect the user all the time. He talked about wire frames and how to use them to mock up your site. He prefers pen and paper over electronic wire frames. He also talked about the importance of consistency and menu placement. I had to leave the session early because I had the next session.

My first session of the day was in the second time slot. I really enjoy the “Software Gardening” session and attendees again told me how much they enjoyed it. Thank you for those words. Software Gardening is the premise that creating software is not like constructing a building. Software is more organic, changing in unexpected ways at unexpected time. Software is more like gardening and needs the same care and treatment. Good soil, water, light, weeding, fertilizing, and other gardening concepts also apply to software development.

After the standard pizza lunch (it’s cheap and easy to feed 500 people this way), I had my second session, “Ooey GUI Web”. This is a new session this year. I cover the basics of JQueryUI, Wijmo, and JQuery DataTables. The session went a bit rough. It was the first time I had given it. But several attendees talked to me afterwards with suggestions for improvement.

After my session, I attended “Building Better Software with TDD” presented by Richard Clements. It’s an important topic but I’d never seen Richard present. I’m glad I was there. He talked not only about the philosophy of TDD, but also the practical. He showed several examples of TDD in action and why you want to develop your applications using TDD.

The final session was “Scrum Challenges” by Richard Hundhausen. The session was presented in a agile way. Attendees wrote questions or problems they have with Scrum on Post-It Notes, which were then put on the front of the podium. Rich would select one and we’d discuss it, then move to another question. It was very effective. One important thing I got out of this session is that there is no such thing as Sprint 0, meaning you don’t plan before you start work. You only plan and design far enough ahead to deal with the first Sprint. Each Sprint after that, you update the design to handle the code you’re writing. Remember, running code is the most important thing to come out of the Sprint.

After the final session, all attendees congregated for the prize drawings. Several companies donated software or hardware. Unfortunately, I didn’t win.

Boise Code Camp was a great day of learning and networking. I hope to make it back again next year.

WP_20130316_006 WP_20130316_009 WP_20130316_007WP_20130316_003


What’s that smell? Code Camp season!

Ahhh.. spring. What a great time of the year. Days are getting longer..and warmer. The smell of rain storms and fresh flowers fill the air. The only bad thing about spring is that is means the end of ski season. But I smell something else. Spring also means Code Camp season is beginning. And I like that.

I’m kicking off my Code Camps tomorrow with a visit to Boise. Boise Code Camp is a great event held on the Boise State University Campus. I don’t like the Smurf Turf, but the tech community in Boise is great.

I’m giving two presentations. The first is a encore presentation of Software Gardening. Here’s the description:

Creating great software is not like construction. It’s more like gardening. In this session you will learn about important software gardening concepts such as soil, water, seeds, light, pruning, insecticide, weeding, and more. Along the way you’ll see processes, concepts, tools, and techniques that you can use in your software gardening project. By applying the ideas presented in this session, your software will be lush, green, and vibrant. This session has often been named “best of Code Camp” by attendees.

The second is a brand new, first time presentations, Ooey GUI Web.

Having a good, consistent, clean UI is important, but how do you do this? In this session we’ll look at free UI widgets to get you going. You’ll see how easy it is to add these widgets to your web pages and see some customization on them too. Along the way we’ll visit jQuery UI, Wijmo Open and more. A basic understanding of jQuery is recommended but not required.

I’m not sure of the times and rooms for these sessions as the schedule isn’t online, but out these sessions. I’m sure you’ll learn something from them.

 


Copyright © 1996-2010 Developer.Blog();. All rights reserved.
iDream theme by Templates Next | Powered by WordPress