• Blog
  • Archive
  • About
  • Contact
Sign in

Welcome to rickardnilsson.net

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.

Top Posts

  • Applying stylesheets dynamically with jQuery
  • ASP.NET MVC 2 Framework and Unity 2.0 Dependency Injection Container
  • Code Kata Cast
  • Dependency injection in ASP.NET MVC with Unity IoC Container
  • Isolate your code from ASP.NET with Moles Isolation Framework

Sites I've visited recently

  • Ninetech - Affärsnytta med IT
  • JetBrains Team City
  • Vimeo

Categories

  • .NET
  • Agile
  • ASP.NET 2.0
  • ASP.NET 3.5
  • ASP.NET MVC
  • BlogEngine.NET
  • C# 2.0
  • C# 3.0
  • CSS
  • Design by Contract
  • Design Patterns
  • iPhone
  • JavaScript
  • Kata
  • Moles
  • TDD
  • Testing
  • Unit testing
  • Unity
  • User tip

Five most recent posts

  • Prime Factors Kata in C#
  • iPhone developer
  • ASP.NET MVC 2 Framework and Unity 2.0 Dependency Injection Container
  • Isolate your code from ASP.NET with Moles Isolation Framework
  • Moles Isolation Framework from Microsoft to be compared with TypeMock Isolator

Tag cloud

  • agile
  • ajax
  • asp.net
  • asp.net 3.5
  • asp.net mvc 2
  • bdd
  • blog
  • blogengine.net
  • c#
  • cocoa touch
  • code kata
  • correction
  • css
  • dbc
  • dependency injection
  • design by contract
  • dom
  • douglas crockford
  • fakes
  • foto
  • getweekofyear
  • gregoriancalendar
  • highlight
  • html
  • httpcontext
  • humble dialog box
  • inversion of control
  • ioc container
  • iphone
  • iphone os
  • iso 8601
  • isolation
  • isolation framework
  • javascript
  • jquery
  • jscript
  • julian bucknall
  • klarsynt
  • live template
  • metaweblog api
  • microsoft research
  • mocks
  • model-view-presenter
  • moles
  • mvp
  • ninetech
  • objective-c
  • patterns & practices
  • photo album
  • picasa
  • recent posts
  • refactor
  • refactoring
  • release
  • resharper
  • rhino mocks
  • roy osherove
  • stubs
  • syntax
  • syntax highlighter
  • tdd
  • tdd masterclass
  • test coverage
  • testing
  • typemock
  • types
  • unit test
  • unity
  • unity 2.0
  • update
  • web service
  • week
  • widget
  • word 2007
  • yahoo
  • yui

Isolate your code from ASP.NET with Moles Isolation Framework

Monday, 19 April 2010 13:33 by Rickard

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

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

Moles Isolation Framework from Microsoft to be compared with TypeMock Isolator

Tuesday, 13 April 2010 13:53 by Rickard

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:  
Share | Comments (1) | |
 
Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
© 2008-2010 rickardnilsson.net
Creative Commons-licens