rickardnilsson.net is a weblog and the online home of web developer and father of three, Rickard Nilsson... More
Rickard blogs about creating software solutions using ASP.NET and agile practices.
Are you new to the concept of code katas? Read my previous blog post and watch me perform the String Calculator Kata.
In my never ending goal of self improvement in the techniques and tools I use I’ve been practicing a version of the Prime Factors Kata for a while.
The Prime Factors Kata, initially sparked by the infamous Uncle Bob Martin, is about finding an arbitrary number’s prime factors. In the cast I show how my TDD practice has evolved into a flavor of BDD, mainly to reduce duplication in the unit tests. I also show off the awesome power of my current toolset which includes the Visual Studio 2010 and the latest versions of ReSharper, TestDriven.NET, NUnit and NBehave.
Though my performance is not yet perfected I want to put it out there because I feel there are no C# version that can really match the Ruby version in elegance and wit. This is my attempt to show what you can do with the C# language in terms of dynamism and when you know the frameworks really well.
Please leave comments and/or suggestions below or record your own kata session in response.
Prime Factors Kata in C# from Rickard Nilsson on Vimeo.
If you are new to the Prime Factors Kata, code katas in general, or TDD for that matter, you may find the steps I take unnecessary or weird. You may want to watch the annotated version in which Uncle Bob explains why each step is taken and why they are taken in that order.
Many have recorded there own versions of the Prime Factors Kata which all inspired me in the way I practice it. The cast that inspired me the most is
there are also a few other C# casts worth watching for comparison by:
Now I’m officially an iPhone developer with an app published on App Store by Ninetech.
Two month ago I hadn’t used a Mac computer in fifteen years when I started studying to become an iPhone developer. Now, I’ve designed, developed and shipped a promotional app on behalf of a client, with no prior experience with Objective-C or Cocoa Touch.
However, I've worked with mobile platforms before on the Compact Framework, but in comparison it was incredibly easy to learn and start working with the iPhone platform. The power that iOS (former iPhone OS) provides to the developer is amazing and it's really easy to get stuff done quickly.
I recommend jumping on the i Phone train.
(N.B! This blog will continue to address web development, despite my new interest)
This is an update to a previous post on MVC and Unity: Dependency injection in ASP.NET MVC with Unity IoC Container
After my previous post, new versions of both ASP.NET MVC and Unity has been released and some confusion about their compatibility has shown up on the Internet. The first hit on Google on the topic is this which is completely wrong and uninformed. BillKrat writes:
"MVC2 will pull the rug out from under these blogs because the IControllerFactory interface for CreateController no longer provides a "type" - it provides a "string" which will simply hold the controllerName; not as easy to work with."
In fact, this is not the case at all. The following snippet is fresh out of the code repository from the MVC 1.0 relase:
public interface IControllerFactory { IController CreateController(RequestContext requestContext, string controllerName); void ReleaseController(IController controller); }
thus, the interface has not changed at all, and all samples on integrating ASP.NET MVC with Unity still apply!
What BillKrat has done is to mistake the interface for the base implementation in System.Web.Mvc.DefaultControllerFactory. If we subclass DefaultControllerFactorty all we need to do is this (as I’ve explained previously):
public class UnityControllerFactory : DefaultControllerFactory { private readonly IUnityContainer container; public UnityControllerFactory(IUnityContainer container) { this.container = container; } protected override IController GetControllerInstance( RequestContext requestContext, Type controllerType) { return container.Resolve(controllerType) as IController; }}
thus, here we get our type which plays very nicely with Unity’s Resolve method.
In the following example I will show how easy it is to isolate your client code from ASP.NET code, using the Moles Isolation Framework, in order to test that your code performs as intended.
The example should not be seen as an encouragement to use bad design. On the contrary, I urge you to use Moles to get that ugly, old legacy code you’ve got, and put it under test such that you will have the freedom to rip it apart and improve it.
Now Moles will generate an assembly with mocks and stubs of the target assembly (System.Web) and add it to the test project. Your references should look like this:
Now you are ready to start writing tests. First we take a look at our sample application. It is a simple ASPX-page which calls Server.MapPath() in the Page_Load method:
public partial class ServerUsageExamplePage : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //... Server.MapPath("...");
//... } }
In our unit test we want to be able to replace the call to Server.MapPath() such that
The following test method will fake the call to Server.MapPath() and assert that it was actually called by the method under test:
[TestMethod] [HostType("Moles")] public void MapPath_WhenCalledWithProperContext_ShouldInvokeServerMethod() { // Arrange var mapPathWasCalled = false; MHttpContext.CurrentGet = () => new MHttpContext { ServerGet = () => new MHttpServerUtility { MapPathString = path => { mapPathWasCalled = true; return string.Empty; } } };
// Act var page= new ServerUsageExamplePage(); page.Page_Load(this, EventArgs.Empty);
// Assert Assert.IsTrue(mapPathWasCalled); }
To accomplish this we need to understand what is going on. “Server” is an instance property on the System.Web.UI.Page class which eventually will invoke the HttpContext.Current.Server property. Thus, to fake the method call we need to fake several things:
Finally, to be able to execute the method under test (Page_Load), we need to change its accessibility from protected to public.
I've shown how easy it is to get started covering your ASP.NET codebehinds with unit tests utilizing Moles Isolation Framework. This article will be followed up with more examples on how to leverage Moles. Please leave feedback and any questions you might have. Good luck testing!
Moles is a new framework from Microsoft Research for isolating objects in unit tests. With the framework you create test stubs by using delegates and you can route any .NET method you want, including non-virtual and static methods in sealed classes. In addition, the framework is free, making it a major competitor to TypeMock Isolator that has been alone on this functionality for a long time.
Moles automatically generates stubs for all classes in one assembly. Here is an example of how easy it is to change the behavior of the static DateTime.Now property:
// change the value of DateTime.Now MDateTime.NowGet = () => new DateTime(2000,1,1); if (DateTime.Now == new DateTime(2000,1,1)) throw new Y2KBugException();
Mole’s strength to fake and reroute static methods and the like makes it a very powerful tool for isolating and unit testing code developed for SharePoint. Microsoft Research has a whitepaper that describes how to get started:
Unit Testing SharePoint with Microsoft Foundation Pex and Moles
Here is a video that introduces Moles:
Update! This still apply in ASP.NET MVC 2 and Unity 2.0. Read more here...
Enabling truly easy testability with ASP.NET MVC Controllers requires a Dependency Injection container. This post is about showing a more real life example of combining Unity with ASP.NET MVC Controllers than the standard demo. Unity is the IoC Container from Microsoft Patterns & Practices and ships as a part of Enterprise Library as well as a stand alone on Codeplex.
We start with the unit test which drives the design of the controller.
[TestMethod] public void Post_PostWithSlugExists_ReturnsResultWithPostAsModel() { controllerContext.RouteData.Values.Add("slug", ValidSlug); var expected = MockRepository.GenerateStub<IBlogPost>(); var blogPosts = new[] {expected}; blogPostService.Expect(s => s.GetPostWhereSlugEquals(slug)) .Repeat.AtLeastOnce() .Return(blogPosts); var controller = CreateController();
var result = (ViewResult) controller.Post(); Assert.AreEqual(expected, result.ViewData.Model); }
Even though the test becomes a bit verbose it clearly states the intent of the controller’s Post method; given the right slug, a result is returned with a blog post as model.
In ASP.NET MVC every request starts in a controller which uses a set of dependencies to do its job. When we have applied Inversion of Control we can inject all of the controller’s dependencies either as a constructor argument or as a property setter. To fully take advantage of this technique we want the dependencies to be automatically injected without creating any of them in overloaded constructors or something like that. This is where the Controller Factory in ASP.NET MVC comes into play.
In the System.Web.Mvc namespace lives the IControllerFactory which implementation is used by the framework to create controller instances. We can use this to swap out the default one and replace it with our own controller factory which uses Unity to create controllers instead.
Instead of implementing all of the IControllerF actory functionallity we can extend the System.Web.Mvc.DefaultControllerFactory and only override what we need.< /p>
public class UnityControllerFactory : DefaultControllerFactory { private readonly IUnityContainer container;
public UnityControllerFactory(IUnityContainer container) { this.container = container; }
protected override IController GetControllerInstance(Type controllerType) { return container.Resolve(controllerType) as IController; } }
In the Global.asax, called MvcApplication in ASP.NET MVC by default, we create our Unity container and tells the MVC framework to use our UnityControllerFactory instead of the default one.
// in Global.asax.cs protected void Application_Start() { RegisterRoutes(RouteTable.Routes);
var container = new UnityContainer(); var controllerFactory = new UnityControllerFactory(container); ControllerBuilder.Current.SetControllerFactory(controllerFactory); }
To illustrate why this is so powerful we will implement a controller that handles requests for blog posts, such as the one you’re reading right now. For this example the controller only handles requests for single blog posts using the post’s slug as identity. A slug is the post’s title made url friendly (e.g. "Dependency-injection-in-ASPNET-MVC-with-Unity-IoC-Container” for this post). The PostController has a dependency on an IBlogPostService which it uses to lookup the blog post to send to the view.
public class PostController : Controller { private readonly IBlogPostService blogPostService;
public PostController(IBlogPostService blogPostService) { this.blogPostService = blogPostService; }
public ActionResult Post() { var slug = GetSlug(); var post = blogPostService.GetPostWhereSlugEquals(slug); return View(post); }
private string GetSlug() { return RouteData.GetRequiredString("slug"); } }
The Post action returns an ActionResult with the post a the model. We can use strongly-typed views to get intellisense in the aspx-file.
<%@ Page /*...*/ Inherits="ViewPage<IBlogPost>" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> <%=Model.Title %> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h2><%=Model.Title %></h2> <p> <%=Model.Body %> </p> <p><%=Html.PostActionLink("Permalink", Model) %></p> <p><a href="/2009/10/10/fail">fail link</a></p> </asp:Content>
<%@ Page /*...*/ Inherits="ViewPage<IBlogPost>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
<%=Model.Title %>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2><%=Model.Title %></h2>
<p>
<%=Model.Body %>
</p>
<p><%=Html.PostActionLink("Permalink", Model) %></p>
<p><a href="/2009/10/10/fail">fail link</a></p>
Notice how the view inherits from ViewPage<IBlogPost> which is key to make the model type of IBlogPost. Then we can use the Post properties to render the blog post in the view.
Combining ASP.NET MVC with Unity or your IoC Container of choice makes your controllers much more easily testable. You only state your classes dependencies as constructor parameters or properties and the container will do the wiring for you. The gives you time to focus on the program logic and the interaction between its components.
After I posted my Code Kata Cast I received some feedback regarding the ReSharper templates I use to speed up my coding. I decided to share them with the public (like so many before me) in hope that others may benefit from them, as I do.
rickardn-resharper-templates.zip (1,44 kb)
After you’ve downloaded the zip-file and unpacked it, open Visual Studio and the ReSharper Templates Explorer: Menu –> ReSharper –> Live Templates…
Click on Import… as the screen shot below shows, and find the file “rickardn-resharper-live-templates.xml”
Then click the “File Templates” tab and repeat the procedure for the “rickardn-resharper-file-templates.xml” file.
Good luck with your katas!
Much of the legacy ASP.NET code I’ve seen is littered with calls to methods on the HttpServerUtility class,
Server.MapPath(…)
Why, if your suite has thousands of tests and many calls IO or datebases, the tests will run slowly, and the developers on the team won’t run them as often. Ultimately, you may loose your investment in automated testing because it isn’t providing the promised feedback.
If the code behind code calls Server.MapPath() it is actually calling the Server property on the Page base class which returns HttpContext.Current.Server. This is an instance of the HttpServerUtility class, which is sealed and thus pretty impossible to fake out*.
In the namespace System.Web.Abstractions, which is part of ASP.NET 3.5, lives an abstraction of the HttpServerUtility, called HttpServerUtilityBase. It has a concrete implementation named HttpServerUtilityWrapper that takes an HttpServerUtility instance as a constructor parameter, as follows:
public sealed class HttpServerUtility { // ... }
public abstract class HttpServerUtilityBase { // ... }
public class HttpServerUtilityWrapper : System.Web.HttpServerUtilityBase { public HttpServerUtilityWrapper(HttpServerUtility httpServerUtility) {} // ... }
By leveraging a simple form of dependency injection we can preserve the old code as a first step of refactoring, and using an overloaded constructor to inject the fake object in our unit test.
public class Presenter { private HttpServerUtilityBase Server; public Presenter(HttpServerUtilityBase httpServerUtility) { Server = httpServerUtility; } public Presenter() { Server = new HttpServerUtilityWrapper(HttpContext.Current.Server); } public void PageLoad() { var path = Server.MapPath(…) } }
Now, in a unit test for the Presenter class we can inject a fake server utility, which won’t call any IO.
[Test] public void PageLoad_WhenCalled_ExpectedBehavior() { var fakeServerUtility = new HttpServerUtilityFake(); // implemented in the test suite var presenter = new Presenter(fakeServerUtility); presenter.PageLoad(); // Assert expected behavior }
Instead of implementing your own fake you can easily use your preferred isolation (mocking) framework of choice.
The goal is to isolate the class under test from all of its dependencies, weather they call IO, a database, a third party component, or even statics or touch static state. The point is that we want to assert that the class under test behaves as expected, not how the underlying framework behaves.
By leveraging the System.Web.Abstractions namespace we can preserve much of the existing ASP.NET code while covering it with tests.
_________ * Unless using TypeMock Isolator
Have you ever come across the concept of a Code Kata?
For me it really took off after reading blog posts (1, 2, 3) by Unce Bob Martin and Pragmatic Programmer Dave Thomas. The concept is really simple: how can we, as programmers, better our selves and improve our techniques and proficiency in using the tools and processes in our every day work?
The suggested solution is inspired by the martial arts kata. You learn how to implement a solution to a specific problem and you practice all the moves in the exact same order over and over again. The point is that you should know the moves so well that you forget about them and focus on improving your key strokes and the use of your tool set. The never ending goal is to perform the kata with the least amount of key strokes.
The promise is that practicing these kata's often and regularly makes you a better and more productive programmer in that you are trained to act instinctively in certain reoccurring situations.
Anyway, I've been practicing a kata based on a problem initiated by Roy Osherove and I decied to record it to get some feedback and maybe spread some knowledge on how I practice Test-driven development using ReSharper.
Calculator Code Kata Cast 1 from Rickard Nilsson on Vimeo.
Roy Osherove is giving an hands-on TDD Masterclass in the UK, September 21-25. Roy is author of "The Art of Unit Testing" (http://www.artofunittesting.com/), a leading tdd & unit testing book; he maintains a blog at http://iserializable.com (which amoung other things has critiqued tests written by Microsoft for asp.net MVC - check out the testreviews category) and has recently been on the Scott Hanselman podcast (http://bit.ly/psgYO) where he educated Scott on best practices in Unit Testing techniques. For a further insight into Roy's style, be sure to also check out Roy's talk at the recent Norwegian Developer's Conference (http://bit.ly/NuJVa). Full Details here: http://bbits.co.uk/tddmasterclass bbits are holding a raffle for a free ticket for the event. To be eligible to win the ticket (worth £2395!) you MUST paste this text, including all links, into your blog and email Ian@bbits.co.ukwith the url to the blog entry. The draw will be made on September 1st and the winner informed by email and on bbits.co.uk/blog
Roy Osherove is giving an hands-on TDD Masterclass in the UK, September 21-25. Roy is author of "The Art of Unit Testing" (http://www.artofunittesting.com/), a leading tdd & unit testing book; he maintains a blog at http://iserializable.com (which amoung other things has critiqued tests written by Microsoft for asp.net MVC - check out the testreviews category) and has recently been on the Scott Hanselman podcast (http://bit.ly/psgYO) where he educated Scott on best practices in Unit Testing techniques. For a further insight into Roy's style, be sure to also check out Roy's talk at the recent Norwegian Developer's Conference (http://bit.ly/NuJVa).
Full Details here: http://bbits.co.uk/tddmasterclass
bbits are holding a raffle for a free ticket for the event. To be eligible to win the ticket (worth £2395!) you MUST paste this text, including all links, into your blog and email Ian@bbits.co.ukwith the url to the blog entry. The draw will be made on September 1st and the winner informed by email and on bbits.co.uk/blog