Rickard Nilsson

  • Blog
  • Archive
  • About
  • Contact

Welcome to rickardnilsson.net

Rickard Nilsson is a software architect, developer, craftsman, agile enthusiast, and father of three... More

Rickard blogs about crafting software using .NET tooling and solid, development practices.

Follow @rickardn

Top Posts

  • Applying stylesheets dynamically with jQuery
  • My customized Son of Obsidian Visual Studio color scheme for ReSharper
  • .NET Development with Visual Studio on MacBook Pro
  • Code Kata Cast
  • ReSharper User tip #2: Refactor rename namespace
  • Combining and minifying JavaScript and CSS files with Ajax Minifier
  • Dependency injection in ASP.NET MVC with Unity IoC Container
  • C# REPL and Interactive interpreter

Categories

  • .NET
  • Agile
  • ASP.NET 2.0
  • ASP.NET 3.5
  • ASP.NET 4
  • ASP.NET MVC
  • BlogEngine.NET
  • C# 2.0
  • C# 3.0
  • C# 4.0
  • Continuous Integration
  • CSS
  • Design by Contract
  • Design Patterns
  • iPhone
  • JavaScript
  • Kata
  • Moles
  • Open source
  • Personal
  • Review
  • Social media
  • Software development
  • TDD
  • Testing
  • Umbraco
  • Unit testing
  • Unity
  • User tip
  • Web development

Five most recent posts

  • How to unit test your database code when using ServiceStack OrmLite
  • Extract class - ReSharper Ninja tricks
  • ASP.NET MVC 3 Template with built in JavaScript and CSS merging and minification
  • ReSharper Ninja tricks - Generate code from usage
  • Unit testing continuously

Tag cloud

  • agile
  • blogengine.net
  • c#
  • code kata
  • codegarden11
  • continuous integration
  • css
  • dependency injection
  • fakes
  • iso 8601
  • javascript
  • jquery
  • refactoring
  • resharper
  • resharper usertip
  • tdd
  • testing
  • umbraco
  • unit test
  • unit testing
  • visual studio

Recent comments

Isolate your code from ASP.NET with Moles Isolation Framework

Monday, 19 April 2010 13:33 by Rickard Nilsson

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.

Prerequisites

  1. Download and install Moles Isolation Framework for .NET
  2. Open your Solution
  3. Create a test project by doing File > Add > New project > Test > Test Project
  4. Add the following references
    1. Microsoft.Moles.Framework
      %MolesPath%\PublicAssemblies\Microsoft.Moles.Framework.dll
    2. System.Web
  5. On the test project: choose Add > New Item…
  6. Choose the Moles template “Moles and Stubs for Testing”
  7. Name it “System.Web.moles”

AddNewItemMoles

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:

MolesReferences

Class under test

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

  1. We won’t get an NullReferenceException
  2. We can control what is returned

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);
}

Under the covers

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:

  1. Static property HttpContext.Current
  2. Instance property Server on HttpContext
  3. Instance method MapPath on HttpServerUtility

Access modifier

Finally, to be able to execute the method under test (Page_Load), we need to change its accessibility from protected to public.

Summary

I've shown how easy it is to get started covering your ASP.NET codebehinds with unit tests utilizing Moles Isolation Framework. Please leave feedback and any questions you might have. Good luck testing!

Tags:   moles, unit test, isolation, testing, mocks, stubs, fakes, asp.net, c#, microsoft research, isolation framework
Categories:   .NET | Moles | Testing | Unit testing | User tip
Actions:   | Ping backs (2)

Moles Isolation Framework from Microsoft to be compared with TypeMock Isolator

Tuesday, 13 April 2010 13:53 by Rickard Nilsson

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();

For SharePoint

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

Introduction

Here is a video that introduces Moles:

PlayButton512

Tags:   testing, unit test, tdd, fakes, stubs, isolation framework, mocks, typemock, microsoft research
Categories:   TDD | Testing | Unit testing
Actions:   | Ping backs (1)

ReSharper templates from the Code Kata Cast

Tuesday, 17 November 2009 15:15 by Rickard Nilsson

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”

resharper_import_template

 Then click the “File Templates” tab and repeat the procedure for the “rickardn-resharper-file-templates.xml” file.

 Good luck with your katas!

 

Tags:   resharper, live template, c#, tdd, unit test, code kata
Categories:   Agile | C# 3.0 | TDD
Actions:  

How to unit test code which depends on HttpContext.Current.Server

Wednesday, 11 November 2009 22:33 by Rickard Nilsson

Much of the legacy ASP.NET code I’ve seen is littered with calls to methods on the HttpServerUtility class,

Server.MapPath(…)

is only one such method. This makes it really hard to test. We need to be able to fake the MapPath method to return exactly what we want without doing the actual file mapping on disk.

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.

  • First of all, if the code is in the code behind of an aspx-file we need to extract as much as possible into its own class, which can be newed up in a unit test.
  • Second of all, we need to extract all external dependencies of the class such that fakes can be injected.

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*.

Solution

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.

Conclusion

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

Tags:   asp.net 3.5, unit test, agile, fakes, httpcontext, dependency injection
Categories:   Agile | ASP.NET 3.5 | Unit testing
Actions:  

Code Kata Cast

Tuesday, 27 October 2009 20:28 by Rickard Nilsson

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.

Calculator kata cast

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.

Tags:   unit test, refactoring, tdd, code kata, resharper
Categories:   C# 3.0 | TDD | User tip | Kata | Unit testing
Actions:   | Ping backs (11)
 
Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
© 2008-2011 rickardnilsson.net
Creative Commons-licens