Using the Should assembly for testing

Posted by Joe Wilson on Monday, August 23, 2010 7:30 AM

Should is a .NET assembly of extension methods for building easy to write and easy to read assert statements.  The advantage of using this assembly is the syntax is more clear and more like human language.  It's free, open source, and it doesn't matter if you're using NUnit or MSTest or any test runner (Test Driven .NET, ReSharper, etc.).  The project is in Beta 1.1, but I've used it on a couple of projects now with no problems.

I've never really liked the MSTest way of doing an assert.  The whole expected and actual arguments always seemed flipped around to me.

// Assert
Assert.AreEqual("eggs", breakfast.Foods.First());
Assert.AreEqual("bacon", breakfast.Foods.Last()); 

Instead, just reference the Should assembly and add the

using Should;

statement to the top of your test code and you can change it to:

// Assert
breakfast.Foods.First().ShouldEqual("eggs");
breakfast.Foods.Last().ShouldEqual("bacon");

I think one of the tricks to writing good tests is to have code that is dead simple to read when you come back to it much later.  The Should assembly gives you that.

Here are some other calls from the CodePlex home page for the project:

        public void Should_String_assertions()
        {
            var obj = new object();
            obj.ShouldBeInRange(1,2);
            obj.ShouldBeNull();
            obj.ShouldBeSameAs(new object());
            obj.ShouldBeType(typeof (object));
            obj.ShouldEqual(obj);
            obj.ShouldNotBeInRange(1,2);
            obj.ShouldNotBeNull();
            obj.ShouldNotBeSameAs(new object());
            obj.ShouldNotBeType(typeof(string));
            obj.ShouldNotEqual("foo");
           
            "This String".ShouldContain("this");
            "This String".ShouldNotBeEmpty();
            "This String".ShouldNotContain("foobar");
            
            false.ShouldBeFalse();
            true.ShouldBeTrue();

            var list = new List<object>();
            list.ShouldBeEmpty();
            list.ShouldNotContain(new object());

            var item = new object();
            list.Add(item);
            list.ShouldNotBeEmpty();
            list.ShouldContain(item);
        }

You should check it out!

Tags:
Categories: Technical


kick it on DotNetKicks.com shout it on DotNetShoutOut

Don't mock HttpContext

Posted by Joe Wilson on Thursday, August 19, 2010 6:40 PM

He doesn't like to be mocked!crying kid

It's so easy to take a direct dependency on HttpContext and not even realize it.  If you're in the code behind in Web Forms or in a controller action in MVC, it's just right there, tempting you to use it to access session variables, application security, etc.

But don't.

Some little known facts about HttpContext:

  • HttpContext is the largest object ever created by humans.
  • If you printed out the code for everything in HttpContext, the pages could be stacked end to end to wrap around the Earth's equator 7 times.
  • Mocking HttpContext is like trying to calculate the last digit of pi.  There is always a little more to it. 
  • Chuck Norris gave up trying to mock HttpContext.  He was deep in HttpContext.Response and quit, curled into a ball on the floor, and started whimpering.

Sealed what?  Object reference what?

Let's say you've got some MVC security stuff you're trying to work with in a controller action.  You've got code like:

    public class OrderController : Controller
    {
        [Authorize]
        public ActionResult Process()
        {
            if (User.IsInRole("Admin"))
            {
                return View("SecretAdminStuff");
            }

            return View("NotAuthorized");
        }
    }

See that User.IsInRole() code?  That call is really to HttpContext.Current.User.IsInRole().  You just took the bait and are tied to HttpContext now.

So what? You have to use HttpContext to get that information, right?  Sure, but you don't want to be tied directly to it or you've created untestable code.

Let's try a couple tests to verify the branching in this action method is returning the correct view based on the user's role.  I'm using NUnit, Rhino Mocks, and the Should assembly below.  Rhino Mocks has .Stub() and .Return() extension methods to set the expected return values for whether the user is or isn't in the Admin role.

        [Test]
        public void Should_return_NotAuthorized_view_when_not_Admin_user()
        {
            // Arrange
            var mockContext = MockRepository.GenerateMock<HttpContext>();
            mockContext.Stub(x => x.User.IsInRole("Admin")).Return(false);
            var orderController = new OrderController();

            // Act
            var result = orderController.Process() as ViewResult;

            // Assert
            result.ViewName.ShouldEqual("NotAuthorized");
        }

        [Test]
        public void Should_return_SecretAdminStuff_view_when_Admin_user()
        {
            // Arrange
            var mockContext = MockRepository.GenerateMock<HttpContext>();
            mockContext.Stub(x => x.User.IsInRole("Admin")).Return(true);
            var orderController = new OrderController();

            // Act
            var result = orderController.Process() as ViewResult;

            // Assert
            result.ViewName.ShouldEqual("SecretAdminStuff");
        }

As soon as we run the tests we see "System.NotSupportedException : Can't create mocks of sealed classes".  Oh yeah, HttpContext is sealed.  That won't work.

Hmmm.  Aren't there some new classes in System.Web.Abstractions for just this kind of thing?  Let's change HttpContext

var mockContext = MockRepository.GenerateMock<HttpContext>();

to HttpContextBase

var mockContext = MockRepository.GenerateMock<HttpContextBase>();

and see if that helps.

The new problem is: "System.NullReferenceException : Object reference not set to an instance of an object."  Mocking HttpContextBase isn't helping because the test isn't passing the mock context into the controller.  Every call in the action method to User.IsInRole() will always call the real HttpContext, which isn't created because the test is not running in the ASP.NET process.

You can get around this with Typemock Isolator, which goes beyond mocking and can intercept the next call to HttpContext.Current.User.IsInRole() and swap out a result, but isn't there a simpler way to do this without buying another product or waiting for better abstract classes to work with?

A better way

We can't test something tied to HttpContext like this.  We need another approach.  The one I favor is wrapping the calls we care about, delegating out to the untestable code in the wrapper class, then passing an interface to the wrapper class into the constructor of the class using it.

Here's the wrapping class I've created to access a few HttpContext current user values and the interface for the wrapping class:

    public class CurrentUser : ICurrentUser
    {
        public virtual string Name()
        {
            return HttpContext.Current.User.Identity.Name;
        }

        public bool IsLoggedIn()
        {
            return HttpContext.Current.User.Identity.IsAuthenticated;
        }

        public bool IsGuest()
        {
            return HttpContext.Current.User.IsInRole("Guest");
        }

        public bool IsAdmin()
        {
            return HttpContext.Current.User.IsInRole("Admin");
        }
    }

    public interface ICurrentUser
    {
        string Name();
        bool IsLoggedIn();
        bool IsGuest();
        bool IsAdmin();
    }

Now I need to update the controller to inject this dependency into the constructor so it can be mocked, and use a private field set in the constructor for subsequent calls to _currentUser:

    public class OrderController : Controller
    {
        private readonly ICurrentUser _currentUser;

        public OrderController(ICurrentUser currentUser)
        {
            _currentUser = currentUser;
        }

        [Authorize]
        public ActionResult Process()
        {
            if (_currentUser.IsAdmin())
            {
                return View("SecretAdminStuff");
            }

            return View("NotAuthorized");
        }
    }

Now we've got a testable action method.  I mock the CurrentUser with MockRepository.GenerateMock<ICurrentUser>, set its return value with the Rhino Mocks .Stub() and .Return() extension methods, and check for the expected results:

        [Test]
        public void Should_return_NotAuthorized_view_when_not_Admin_user()
        {
            // Arrange
            var mockCurrentUser = MockRepository.GenerateMock<ICurrentUser>();
            mockCurrentUser.Stub(x => x.IsAdmin()).Return(false);
            var orderController = new OrderController(mockCurrentUser);

            // Act
            var result = orderController.Process() as ViewResult;

            // Assert
            result.ViewName.ShouldEqual("NotAuthorized");
        }

        [Test]
        public void Should_return_SecretAdminStuff_view_when_Admin_user()
        {
            // Arrange
            var mockCurrentUser = MockRepository.GenerateMock<ICurrentUser>();
            mockCurrentUser.Stub(x => x.IsAdmin()).Return(true);
            var orderController = new OrderController(mockCurrentUser);

            // Act
            var result = orderController.Process() as ViewResult;

            // Assert
            result.ViewName.ShouldEqual("SecretAdminStuff");
        }

Hey, wait a sec.

If you're thinking to yourself: I've just tested the code in the action method and not whether HttpContext really works, you're exactly right.  The tests should cover the branching in the controller action and are unit tests.  They are not integration tests that check to see if HttpContext is returning the right values.

I'm OK with that tradeoff.  I know HttpContext works.  It's been around forever and it's in a System.<something> namespace, so I shouldn't be testing it. 

The real question is, do my login and roles and authorization settings work as expected in my application.  That calls for integration testing, and the easiest way to do that is click through those screens and see if it's working.  You can also automate this clicking around with Watin, or SpecFlow (which uses Watin internally to drive the browser).

Tags: , , , , , , ,
Categories: Technical


kick it on DotNetKicks.com shout it on DotNetShoutOut

Do we still need coding standards?

Posted by Joe Wilson on Tuesday, July 6, 2010 6:31 PM

The dark ages

I used to be really big on coding standards in the late 1990's.  It was so easy to slip into spaghetti code in classic ASP and VB6, and at the time, the best antidote was rigid standards and uncompromising code reviews. 

I was a hard ass about our coding standards.  Then, as now, the rationale was that coding standards would make the code easier to read and maintain in the inevitable and long maintenance phase.

The development process we used at the time was to stand around the white board and talk about the development tasks, then the developers would go off and separately code it up.  That was the other reason the coding standards mattered - we didn't want two code files to look totally different if written by different developers.

My teams used the naming conventions Microsoft came up with for Access/VBA/VB, including Hungarian notation prefixes, but a lot of the standards were about code comments, error handling code, whitespace and indenting, etc.

.NET comes on the scene

Fast forward maybe 5 or so years to the introduction of .NET and C#, and coding changed.  ASP.NET HTML didn't require <% %> tags anymore.  We could put the C# in code behind files and other project files.  We didn't need On Error anymore, we had Try-Catch.  XML comments seemed like a cool feature to show Intellisense drop downs for code you wrote in addition to framework Intellisense.

So we updated our coding standards to reflect the language and IDE changes, but they became more like guidelines instead of hard and fast rules.  By convention, we would avoid the spaghetti code just by keeping the right code in the right place.  Hungarian notation went away (slowly but surely).  The coding standards document was mostly reference code snippets and justifications for the conventions we used.  Code reviews became less common because it wasn't as big of an issue.

Today

A lot has changed since .NET first came out, and I code differently now.  I'm trying to make my code a lot more terse these days.  I'm a big fan of having clean, succinct, expressive code.  The fewer non-essential things on the screen to wade through, the better.  It's more readable and easier to refactor.

  • I could put Try-Catch blocks everywhere, but isn't it simpler to catch unhandled exceptions in one place.
  • I could add XML comments, but why?  It's either code in my same web project or a project that is owned by my solution.  I don't usually work on common library code where an assembly will be used across projects and Intellisense might be needed.
  • I don't put the variable type on the left side of the equal sign anymore and use "var" instead.
  • I've walked away from code regions and just order the items in the class file by convention.  ReSharper likes to put new fields under the last field declaration in the class, so region wrapping all the fields in a class with "#region Fields" just wastes time when refactoring to pull it back up into the region.

Not only has the way I code changed, but the tools have changed. ReSharper code cleanup templates and StyleCop warnings can be used to keep your team writing code in a style that you've all agreed on.  Just run the tool and have it clean up the code for you or flag code that doesn't meet the style guidelines.

Having tests around the code lets me refactor and use auto-code-cleanup tools freely.  I understand the project a little more fully every day, so I can rename my class, method, and variable names to be more descriptive and accurate without worrying about breaking code.

I'm also doing more pair programming these days, and this is a good way to enforce and socialize team coding styles.  It also means we don't have to refer to a coding standards document as often.  Since we're more story-focused, we're thinking more about the feature and less about coding style.  Taking ceremony code off the screen helps us keep that focus.

If I had to do it over

If I was going to write a coding standards document today, it would be more like a style guide to reflect my current less-is-more thinking, and I'd probably give my peers a ReSharper template to auto-clean their code as they go instead of a document to refer to.  StyleCop for ReSharper looks promising as a gentle background reminder of team coding styles.

What about your team?  Do you have a coding standards document people refer to?  Do you use tools to enforce standards/styles?

Tags: , ,
Categories: Technical


kick it on DotNetKicks.com shout it on DotNetShoutOut

Unit testing untestable code

Posted by Joe Wilson on Tuesday, April 6, 2010 1:44 PM

Let’s say you’ve got a static or sealed class, or a class with non-virtual members that your code needs to use.  You need to unit test your code, but you can’t get an instance of this class and/or you can’t mock it. 

There are two ways to go:

  1. Buy a tool that let’s you mock things like this, such as Typemock Isolator or the newly announced Telerik JustMock.
  2. Code around it.

Buy it

I’ve already compared Typemock Isolator ($799) to RhinoMocks (free).  Typemock Isolator works as advertised.  The biggest issue is the price.  It’s hard enough to get management approval for introducing external tools.  But when buy-in literally means BUY in, it’s even harder.

Build it

Don’t despair if you’re stuck with “code around it” and using free mocking tools!  If you can change the code that is static, sealed, private, non-virtual, etc. fix it that way.  That’s the best thing.

But if it’s in a legacy assembly you have to use, and you can’t just change the original code, use this simple technique. 

Here’s the untestable class we need to use.  It’s static, so we can’t mock an instance of it with Rhino Mocks.

public static class StaticSendOrderClass
{
    public static void SendOrderToAccountsPayable(Order order)
    {
        // Pretend code here...
    }
}

Here’s the new code you’re working on that uses this static class to process an order:

public class OrderProcessor
{
    public void ProcessTheOrder(Order order, bool useStaticClass)
    {
        if (useStaticClass == true)
        {
            StaticSendOrderClass.SendOrderToAccountsPayable(order);
        }
        else
        {
            // Notify accounts payable some other way
        }
    }
}

First, we need to create an interface with just the functionality we need from the untestable class.  Name the class and method(s) whatever makes sense for your app.  You’re not tied to the legacy code naming convention; this is your code now.

public interface INotifyAccountsPayable
{
    void SendOrder(Order order);
}

Next, create a new class to implement this interface and wrap the untestable code.  In the method calls in the new class, turn around and delegate the call to the untestable class.

public class NotifyAccountsPayable : INotifyAccountsPayable
{
    public void SendOrder(Order order)
    {
        StaticSendOrderClass.SendOrderToAccountsPayable(order);
    }
}

Now inject the new interface into the constructor of your new class as an argument.  You’ll also want to create a private field and set its value to the instance argument in the constructor.  Now you can swap out your old code that calls the untestable code, and instead use your new private field.

public class OrderProcessor
{
    private readonly INotifyAccountsPayable _notifyAccountsPayable;

    public OrderProcessor(INotifyAccountsPayable notifyAccountsPayable)
    {
        _notifyAccountsPayable = notifyAccountsPayable;
    }

    public void ProcessTheOrder(Order order, bool useStaticClass)
    {
        if (useStaticClass == true)
        {
            _notifyAccountsPayable.SendOrder(order);
        }
        else
        {
            // Notify accounts payable some other way
        }
    }
}

Now you’ve got a unit testable OrderProcessor class!  Mock the INotifyAccountsPayable interface with Rhino Mocks and inject that mocked dependency into your class under test.  Then you can verify the call was made as expected.

[Test]
public void Should_call_untestable_code_when_useStaticClass_is_set_to_true()
{
    // Arrange
    var mockNotifyAccountsPayable = MockRepository.GenerateMock<INotifyAccountsPayable>();
    var orderProcessor = new OrderProcessor(mockNotifyAccountsPayable);
    var stubOrder = MockRepository.GenerateStub<Order>();
    var useStaticClass = true;

    // Act
    orderProcessor.ProcessTheOrder(stubOrder, useStaticClass);

    // Assert
    mockNotifyAccountsPayable.AssertWasCalled(x => x.SendOrder(stubOrder));
}

Please note this is not testing the internals of the untestable, static code.  But you don’t need to worry about unit testing the internals of that code.  You don’t own that code.  Testing that is really an integration test, not a unit test.  Using this approach, you isolate your new code from an external dependency and keep all your new code testable.

Tags: , ,
Categories: Technical


kick it on DotNetKicks.com shout it on DotNetShoutOut

REST-like behavior with MVC instead of WCF

Posted by Joe Wilson on Sunday, March 7, 2010 6:16 PM

WCF is a very cool framework for adding an abstraction layer over your services.  You can have .asmx, .svc, and now, REST URLs with no extension.  These endpoints can even return JSON to the caller, which is useful if you’re using jQuery or another JavaScript library.

The knock on WCF?  The configuration story!  It’s getting better in WCF 4, which is scheduled for release in a month or so.  It will have a bunch of defaults so you don’t have to be as explicit in your config file.  Finally, some convention over configuration in the WCF space!  Now someone needs to create a fluent, code-based configuration tool for the exceptions to the default conventions…

Don’t be afraid of JSON!

Jason But if you need to return JSON to a caller today, you don’t need scary WCF config files to do it.  You can get the same URL and the same data payload with a lot less hassle using MVC controller actions.

The steps are:

  1. Create a new action in a controller.
  2. Grab your data or whatever you want to return.
  3. Parse your data to JSON.
  4. Throw it back out to the requestor.

The trick is to use JsonResult as the return type for your controller action and convert your output to a JSON string with the base controller’s Json method:

public JsonResult GetAllDepartments()
{
    var departments = _repository.GetAllDepartments();
    return Json(departments);
}

Now if I browse to this controller action (I’m using the HomeController in this example):

http://localhost/Home/GetAllDepartments

I get a pop-up to save the response stream, which I can open with Notepad:

[{"Name":"Human Resources"},{"Name":"Accounting"},{"Name":"IT"},{"Name":"Pencil Sharpening"}]

Yeah, JSON!  And there was no gory config setup needed!

Using jQuery with JSON

Now we can use jQuery in the MVC view to take advantage of this returned JSON. 

Here’s a view that has a button and a div tag.  jQuery is being used to tie the button click to a call to the controller and action we set up above.  It then gets the JSON coming back, loops through it, and puts it in the div tag so it’s visible to the user.

<script src="../../Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
    
<script type="text/javascript">
    $(function() {
        $("#btnShowDepartments").click(function() {
            $.getJSON("/Home/GetAllDepartments", null, function(data) {
                for (item in data) {
                    var department = data[item];
                    $("#divDepartments").append(department.Name, ", ");
                }
            });                
        });
    });        
</script>   

<p>
    <input id="btnShowDepartments" type="button" value="Show Departments" />
    <div id="divDepartments"></div>
</p>

This is probably not the best jQuery in the world.  I’m still new to it.  But the point is to show that you can put a URL in, parse the JSON, and use the data however your app needs it.

Tags: , , , ,
Categories: Technical


kick it on DotNetKicks.com shout it on DotNetShoutOut

Increasing Testability

Posted by Joe Wilson on Sunday, March 7, 2010 4:30 PM

Testa-what?

I don't know if "testability" is a word, but if Bud Light can make up "drinkability", maybe it should be.  I'm talking about how pliant your code is to testing.  If you're doing TDD or BDD, the code you write is testable by definition. 

But if you're going the other way, and coding first or testing legacy code (any code not already under test), you've probably run into code that was hard to test and felt like giving up.  Some of the most common hurdles for testability are not coding to abstractions and not decoupling dependencies.  Here's how to get around that.

The problem

Here's a garden variety Order class with a ProcessOrder method:

public class Order
{
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public string Email { get; set; }
  public decimal Total { get; set; }

  public bool ProcessOrder()
  {
    var result = false;
      
    // Validate order
    if (!string.IsNullOrEmpty(this.Email) && this.Total > 0)
    {
      // Send order confirmation email
      var emailService = new EmailService();
      var emailSendResult = emailService.SendOrderConfirmationEmail(this);

      if (emailSendResult == true)
      {
        // Do more order processing...

        result = true;
      }
    }

    return result;
  }
}

And here's the test:

[Test]
public void Should_return_true_when_using_good_order_values()
{
  // Arrange
  var order = new Order();
  order.FirstName = "Joe";
  order.LastName = "Wilson";
  order.Email = "real_email_address@volaresystems.com";
  order.Total = 123.00m;

  // Act
  // Watch out!  Don't run this or it will send real emails!
  var result = order.ProcessOrder();

  // Assert
  Assert.That(result, Is.True);
}

We need to call the SendOrderConfirmationEmail method in the EmailService class.  But if our test calls ProcessOrder, there is no way to avoid calling the live emailing method as it's coded now.

How can we test the logic in the ProcessOrder method without sending out a real email?

Code to Abstractions

First, we need to code to an abstraction of EmailService, not to the concrete class itself.  So let's create an interface around EmailService:

public interface IEmailService
{
    bool SendOrderConfirmationEmail(Order order);
}

Then change the EmailService class to implement this new interface.  Visual Studio 2008 and ReSharper make this easy. 

This will let us change our test later to use a fake version of IEmailService instead of the real one.

Decouple and Invert your Dependencies

The next problem is we're creating an instance of the EmailService class in the ProcessOrder method.  Anytime you use "new" in your code, you're probably introducing a dependency and reducing testability. 

The fix is to let the caller create the instance and tell the class or method being called which instance to use.  I am using a private field with constructor injection to set the field instance.  Note we're also now coding to the interface IEmailService instead of the instance EmailService.

Here's the full Order method using the private field to call the SendOrderConfirmationEmail method on IEmailService inside the ProcessOrder method.

public class Order
{
  private readonly IEmailService _emailService;

  public string FirstName { get; set; }
  public string LastName { get; set; }
  public string Email { get; set; }
  public decimal Total { get; set; }

  public Order(IEmailService emailService)
  {
      _emailService = emailService;
  }

  public bool ProcessOrder()
  {
    var result = false;
      
    // Validate order
    if (!string.IsNullOrEmpty(this.Email) && this.Total > 0)
    {
      // Send order confirmation email
      //var emailService = new EmailService(); // Created outside this class now
      var emailSendResult = _emailService.SendOrderConfirmationEmail(this);

      if (emailSendResult == true)
      {
        // Do more order processing...

        result = true;
      }
    }

    return result;
  }
}

Dependencies can be very hard to spot, but it's critical to tease them out of your code to increase testability.  They can even come from things as innocuous as DateTime.  If you're code relies on DateTime.Now, how will you write unit tests for your logic without changing your system clock when you run the test?  It's simpler to have the caller pass in the DateTime value and have the method do the calculations based on whatever value it is given.

Make a Fake

Now that we've got testable code, we can make a fake EmailService and update our test.

First, create the FakeEmailService class implementing the IEmailService we created earlier.  We need the SendOrderConfirmationEmail method to return true to simulate an email being successfully sent.

public class FakeEmailService : IEmailService
{
  public bool SendOrderConfirmationEmail(Order order)
  {
    return true;
  }
}

You could also use a mocking framework like Moq or Rhino Mocks for this, but a homemade fake is easy, too.

Now we're ready to update our test to use the fake and inject it into the Order constructor:

[Test]
public void Should_return_true_when_using_good_order_values()
{
    // Arrange
    var emailService = new FakeEmailService();
    order = new Order(emailService);
    order.FirstName = "Joe";
    order.LastName = "Wilson";
    order.Email = "real_email_address@volaresystems.com";
    order.Total = 123.00m;

    // Act
    var result = order.ProcessOrder();

    // Assert
    Assert.That(result, Is.True);
}

Last step

We've refactored the Order class so the caller sends the IEmailService instance to it.  That makes sense for the test, but what about the real code?

I typically use an IOC container like Structure Map or Castle Windsor to hold and resolve an in-memory dictionary of interfaces and class instances.  You wire it up at application startup and when you call something that needs IEmailService, it creates an instance of EmailService for you.

If you're working with legacy code and can't use and IOC container, you also can add a no arg constructor like this:

public Order() : this(new EmailService())
{
}

public Order(IEmailService emailService)
{
    _emailService = emailService;
}

Your legacy code keeps calling the no arg constructor like it used to, and any new code and your test code use the constructor with IEmailService dependency passed in.

Wrap up

If you code isn't testable, you won't test it.  If you're working with legacy code or writing tests after coding, you can use these techniques to pull out external dependencies so they can be faked for testing. 

You can have it all: testable code, unit tests around that code, and no broken legacy code.  Mmmm.Testability.Drink it in!

Tags: , ,
Categories: Technical


kick it on DotNetKicks.com shout it on DotNetShoutOut

MVC 2: Electric Boogaloo - What's new in MVC 2

Posted by Joe Wilson on Sunday, January 17, 2010 3:28 PM

The MVCbreakin2 team loves their rec center, but an evil real estate developer wants to bulldoze it to build a hipster bar named Ruby's.  The team has been coding their butts off with MVC 2, but will the new features be enough to save the rec center?  Will the cynical real estate developer cackle and complain that it's still not enough? 

Will the MVC team get areas right?  Will the new templated HtmlHelpers strike the right balance of rapid development and fine control?  Will validation concerns get muddled up with UI concerns?  Will more web forms developers make the switch to MVC? 

New Areas

Areas are an organizing tool for large web sites.  If you've got lots of view and lots of controllers plus some shared content, areas can work as a top-level routing mechanism. 

Example areas might be Admin for an administrative site, Store for a ecommerce site, etc.  They can be either folders or separate web projects.  Use the AreaRegistration class to set up your routes in your Global.asax (taken from MSDN article):

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    AreaRegistration.RegisterAllAreas();

    routes.MapRoute(
        "Default",                                              // Route name
        "{controller}/{action}/{id}",                           // URL with parameters
        new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
    );
}

Then override AreaRegistration in the area's folder or in the root of the area web project (also taken from MSDN article):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Store
{
    public class Routes : AreaRegistration
    {
        public override string AreaName
        {
            get { return "Store"; }
        }

        public override void RegisterArea(AreaRegistrationContext context)
        {
            context.MapRoute(
                "Store_Default",
                "Store/{controller}/{action}/{id}",
                new { controller = "Products", action = "List", id = "" }
            );
        }
    }
}

Sharp Architecture has had areas since its first release.  I remember hearing rumors about areas coming in MVC for version 1.0, but I guess it wasn't ready.  The biggest difference between the Microsoft version and the Sharp Architecture version is that the Microsoft version lets you register different web projects. 

Theoretically, multiple teams can work on multiple web projects, then these web projects can be rolled into the same solution and AreaRegistration can make them appear as one big web site to a browser.  I don't know how much of a need that is, but I guess if you have distributed teams that can't get to the same source code repository, it might be useful.  I prefer multiple folders in one web project over multiple web projects to keep build times down and Visual Studio responsiveness up.  I wouldn't break out each logical web site section to its own web project until the folder approach stopped working.

New HtmlHelpers

I'm not sure if Code Camp Server pushed the MVC team into this or just showed how it was possible to take HtmlHelpers to this extreme, but I'm glad to see the same concepts getting rolled into the base class libraries. 

I think the new HtmlHelpers do give a nice range of control over your markup.  You can use:

<%= Html.LabelFor(x => x.FirstName) %>
<%= Html.EditorFor(x => x.FirstName) %>
<%= Html.LabelFor(x => x.LastName) %>
<%= Html.EditorFor(x => x.LastName) %>

if you want to be fairly explicit for each form element.  Or you can save a lot of keystrokes with:

<%= Html.EditorFor(x => x) %>

And if that's not enough, you can decorate your models with some UI hint attributes and roll your own rendering.  I think this is something large web projects will take advantage of for consistent markup and control rendering.  Seems like this has the advantages of homemade server controls without some of the hassles (INamingContainer, I'm looking at you).

New Validation

I did worry for a little bit about the UI stuff bleeding into the model with these new attributes.  Seems like we've got a leaky abstraction there.  But these days I think of the MVC model as the view model, not the domain model.  The view model is married to the view it works with.  It has no other purpose than to represent the data in that view.  Well, now it also validates the data in that view, at least initially.  Oh, and it now controls some of the view rendering.  Damn.  That's three responsibilities for my little view model.

But I don't have an alternative proposal to attribute-heavy view models either.  I don't want partial classes.  I haven't seen much benefit to the buddy class approach.  And I do want to reuse some of my UI hints across view models (like a date picker for DateTime types).  Plus, I want to take advantage of the new client and server side validation of my view model before it gets into the action method.  MVC 2 has this built in.

I guess I'll grin and bear it and work on a new blog post about the Triple Responsibility Principal for View Models (as opposed to SRP). :D

Future

I've already talked about where MVC views are now and where they are going, and the view engine is definitely getting better. I still think views will continue to be the most in-flux part of the MVC framework.  I know people that are very happy with Spark as a view engine, and Louis DeJardin, the guy who wrote Spark, is now working for Microsoft on the ASP.NET team.  I don't have any inside scoop, but I wouldn't be surprised if the web forms view engine got a little."sparkier".

Views may also be the area with the most room for improvement, depending on who you talk to.  When I visit with people about MVC and explain that runat="server" is gone and you can go ahead and close your Visual Studio toolbox, most get a glazed look.  They don't want to hand code the HTML.  They don't want to see a property sheet that doesn't know anything about their current mouse selection.  They don't want to give up their current productivity.

I get that, but I think you can be faster without the designers and toolboxes and property sheets.  It takes a while to get used to using the keyboard more than the mouse, but I think it's worth pushing yourself over that learning curve.

Time to switch from Web Forms to MVC?

I push MVC on projects where I have influence on that decision.  In your world, it's your call.  You may have environment constraints, in-flight projects, etc. 

But it also doesn't have to be all or nothing.  You don't have to wait for a greenfield project to fall in your lap.  You can run MVC inside your current Web Forms project.  It's just another set of HttpHandlers living under ASP.NET.  Here is some guidance for getting your current project set up to do this.

I encourage you to give it a try and see what you think.  It will take a while to get used to the paradigm.  It's not hard - just different.  But I think once you're used to it, you'll like the separation of concerns, the easier testing, and the more natural flow for web development. 

By natural flow, I mean embracing the world of GET and POST.  I mean when you need to expose JSON, an RSS feed, or something else (XML, PDF, file, etc.), Controller Actions are ready to go.  Stop writing custom HttpHandlers or fighting WCF configuration for this stuff.  It should be simpler, and it is with Controller Actions and the right ActionResult.

Make it a goal to get some real-world MVC experience in 2010.  Think of the kids on the MVC team and their beloved rec center.  Don't let their dream die.  They've come too far.  And remember the tag line from Breakin' 2 - "If you can't beat the system.break it!".

Tags: , , , , ,
Categories: Technical


kick it on DotNetKicks.com shout it on DotNetShoutOut

Why Web Forms isn't as bad as it used to be

Posted by Joe Wilson on Friday, January 8, 2010 7:13 PM

I prefer using MVC over Web Forms for ASP.NET development, but the reasons are getting narrower as Web Forms is improving.  Here's my "Why should I use MVC" list from a recent presentation:

  • To get separation of concerns right from the start
  • To avoid ViewState page bloat
  • To avoid messy HTML
  • To avoid messy URLs

But a lot of this is changing in Web Forms with ASP.NET 4.

ViewState Improvements

In previous Web Forms versions, you could disable ViewState for the page with EnableViewState="False", but the controls on your page still had their own ViewState.  You had to explicitly turn it off for every control in the page to make it really go away.

Now there is a ViewStateMode property that the controls in the form pay attention to.  You can disable ViewState for the page with:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Default"  ViewStateMode="Disabled" %>

And just set ViewStateMode="Enabled" for controls where you need it.  This is the way it probably should have worked all along.  You'll still have view state, but you turn it on where it makes sense instead of having it on all over the place clogging up your response.

Rendered HTML Improvements

Now that we're all doing more client-side development with JavaScript once again, we need to grab control IDs.  We've all seen view source screens with nightmare IDs like:

<span id="ctl00_MainContent_uxdPHAllContent_TripSelector_lblFromDate">
From Date:
</span>
<input type="text" name="ctl00$MainContent$uxdPHAllContent$TripSelector$txtFromDate" id="ctl00_MainContent_uxdPHAllContent_TripSelector_txtFromDate" />

This happens when server controls are nested inside other server controls.  If you use Master Pages and ContentPlaceHolders, everything looks like this.

Now there is a ClientIDMode property of controls.  You can set ClientIDMode="Static" in the container control to get your exact ID or set ClientIDMode="Predictable" to get an ID you can expect in the rendered HTML.

Another rendering improvement coming in Web Forms is in the ControlRenderingCompatibilityVersion property.  It's a mouthful, but set that guy to 4.0 (side note: why "4.0" instead of just "4"?) in your web.config:

<pages controlRenderingCompatibilityVersion="4.0"/>

You get XHTML 1.0 Strict markup, menu HTML that look like a list (UL and LI tags), and fewer inline style setting like on validation controls.

URL Improvements

You're Marketing department has probably asked you for tighter, prettier URLs at some point.  Vanity URLs are a marketer's dream.  With MVC, creating clean, simple URLs is easy.  Now Web Forms has that same goodness.

The MVC URL routing engine is in System.Web.Routing, so it's not just for MVC anymore.  You can get those URLs marketers always want like http://mysite.com/CoolNewProduct without the coding hassles of old.

Conclusion

Web Forms will still have the post-back model, and MVC will still have Controllers with Actions.  And I would still rather work on an MVC project versus a Web Forms project.  But that can now mostly be for architectural reasons rather than framework artifact reasons.

I like the separation of concerns in MVC better, and I think once you get used to routing and Controllers and Actions in MVC, the Web Forms model seems very un-web like.  I also think MVC projects are much more testable. 

But I am glad to see Microsoft making these improvements in Web Forms.  It was due for some tidying up!

Tags: ,
Categories: Technical


kick it on DotNetKicks.com shout it on DotNetShoutOut

Specifying Args with Rhino Mocks

Posted by Joe Wilson on Wednesday, November 25, 2009 4:33 PM

The problem

I ran into a snag testing some code today with Rhino Mocks.  I was mocking calls to a repository and inspecting the repository method calls and arguments passed.

Everything started off pretty normal with the repository dependency injected into the class under test:

// Arrange
var repository = MockRepository.GenerateMock<ICustomerRepository>();
var passenger = new Passenger(repository);

// Act
passenger.CallTheMethodUnderTest(arg1, arg2);

In my Assert section, I needed to check that the correct repository methods were called with the correct arguments.  The catch was, one of the arguments was a class created within the method under test.  I thought I could create and assert the equivalent Customer in my test like this:

// Assert
var expectedCustomer = new Customer
                           {
                               CustomerID = "1234",
                               FirstName = "Joe",
                               LastName = "Wilson"
                           };
repository.AssertWasCalled(x => x.SomeRepositoryMethod(
    arg1, 
    arg2, 
    expectedCustomer));

The two Customer objects (in the test and in the method under test) had the same values, but of course, were not the same objects.  They were two different Customer objects that happened to have the same values.  So Rhino Mocks told me that my expected Assert wasn't met.

The answer

I knew Rhino Mocks could ignore arguments with

Args<T>.Is.Anything

But I knew what the values should be.  In fact, for this test, the values being passed into the repository calls were just as important as the calls themselves.

So I tried comparing the values of the two Customer objects instead of the objects themselves:

repository.AssertWasCalled(x => x.SomeRepositoryMethod(
    arg1,
    arg2,
    Arg<Customer>.Matches(c => 
        c.CustomerID.Equals("1234") &&
        c.FirstName.Equals("Joe") &&
        c.LastName.Equals("Wilson"))));

So close!  But now Rhino Mocks told me if I used Arg for one parameter, I'd better use it for all of them.  No biggie. I made the change and this worked:

repository.AssertWasCalled(x => x.SomeRepositoryMethod(
    Arg<int>.Is.Equal(arg1),
    Arg<int>.Is.Equal(arg2),
    Arg<Customer>.Matches(c => 
        c.CustomerID.Equals("1234") &&
        c.FirstName.Equals("Joe") &&
        c.LastName.Equals("Wilson"))));

Postmortem

The Arg statement let's you specify a type and tell Rhino Mocks you don't know or don't care about the value:

Args<int>.Is.Anything

You can also tell Rhino Mocks you know the type and what the value should be:

Args<int>.Is.Equal(7)

If you have a non-primitive type or complex assert, you can also inspect values with the Matches statement:

Arg<Customer>.Matches(c => 
    c.CustomerID.Equals("1234") &&
    c.FirstName.Equals("Joe") &&
    c.LastName.Equals("Wilson"))));

I realize the code in these tests is probably way too familiar with the code under test.  I prefer testing state over this kind of interaction testing where possible.  But this was a case where the code under test had a void return and didn't do much besides parse some values and call repository methods based on those values.

In times like this, I'm glad I have interaction testing to fall back on so I can verify my code is behaving the way it should.

Tags: ,
Categories: Technical


kick it on DotNetKicks.com shout it on DotNetShoutOut

Moving a VM to another machine

Posted by Joe Wilson on Monday, November 16, 2009 5:49 PM

I've got a work laptop with a VMware virtual machine.  But I wanted to move it to my slightly faster personal rig, with the nicer keyboard, mouse, dual monitors, etc.

So I shut down the VM on the work laptop and copied it over to the personal machine.  Then I downloaded and installed the VMware Player to the new machine, copied the VM to it, and opened it up.  I got a prompt asking if I "moved" or "copied" the VM.  I chose "copied".

The VM spun for a little while, and then there was some gibberish message about VT being possible but disabled on the host.  VT = Vermont?  VT = Virginia Tech? VT = WTF?  I did what professional developers are trained to do in these situations.  I ignored it and clicked OK.

The VM said "Windows in Loading Files." but it kept rebooting over, and over, and over.

I got a tip from David Yack to check the BIOS settings.  I have a Dell Latitude, so your mileage may vary here, but in my BIOS settings, I go to Post Behavior, then Virtualization, then set it to Enabled, then save settings and reboot.

That worked!

Tags:
Categories: Technical


kick it on DotNetKicks.com shout it on DotNetShoutOut

Image Details