A Good TDD Process Diagram?

I am trying to create a flow diagram that depicts the Test Driven Development process and I need your expertise/opinion/criticism in nailing it down.

Take a look below and let me know what is wrong, what is right and what can be done better.


I drew the above diagram based on my understanding of TDD and by referencing other diagrams that I found online.  Specifically:


from http://www.agiledata.org/essays/tdd.html


from http://designindrive.com/?p=31


from http://tinyurl.com/498pjg

Mocking and Dependency Injection in ASP.NET MVC

Here is the situation, my controller constructors take multiple interfaces as parameters.  I do this in order to use constructor injection which allows me to inject the controllers with mocked objects in my unit tests.

For example, my AccountController takes IEmailService, IFormsAuthentication and MembershipProvider (abstract class) as parameters.

During my testing, I want to mock the email, authentication and membership calls.  For example when the user calls FormsAuthentication.Login, I don’t really care if actual call succeeded but rather that my login action works appropriately in the case FormstAuthentication.Login succeeds (or fails).  I just want to mock that call.

I started off creating a few tests and slowly they have grown to several.  There was a lot of repeated code in my unit tests and to be a good citizen of the DRY universe, I needed to refactor the code.

For IoC, I initially started with StructureMap but now I am using Ninject

I created this module to bind my interfaces to mocked instances.  It looks like this:

internal class TestModule : StandardModule
    public override void Load()

Notice that I bind the interfaces to actual instances and not classes.  These instances are declared in a global static class that will be accessed from my unit tests.  As you can tell from the name, they are all mocked objects (I am using Moq).  Here is how the MockEmailService looks (all the others are declared the same way):

internal static class MyMocks
    private static Mock<IEmailService> _mockEmailService;
    public static Mock<IEmailService> MockEmailService
            _mockEmailService = _mockEmailService ?? new Mock<IEmailService>();
            return _mockEmailService;


So all this is good to setup Ninject and create my mocks.  Now I want to easily and generically create a controller, so I can quickly create unit tests.  In order to do that, I created a TestControllerFactory class that basically creates a controller with all the appropriate dependencies injected.

   1: internal static class TestControllerFactory
   2: {
   3:     private static IKernel _kernel;
   4:     public static IKernel Kernel
   5:     {
   6:         get
   7:         {
   8:             if (_kernel == null)
   9:             {
  10:                 var modules = new IModule[] { new TestModule() };
  11:                 _kernel = new StandardKernel(modules);
  12:             }
  13:             return _kernel;
  14:         }
  15:         private set
  16:         {
  17:             _kernel = value;
  18:         }
  19:     }
  21:     public static T GetControllerWithFakeContext<T>(string httpMethod) 
  22:         where T : Controller
  23:     {
  24:         var con = Kernel.Get<T>();
  25:         con.SetFakeControllerContext();
  26:         if (con != null) con.Request.SetHttpMethodResult(httpMethod);
  27:         return con;
  28:     }
  30: }

In line #10, I use the TestModule class mentioned above to setup the Ninject Kernel.  In lines #21 to #28, I create an instance of T which must be of type Controller from the Kernel which will automatically create the Controller with all the mocked objects.  In line #25 and #26, I just set a fake/mocked context and the Http Method for the request (more info here).

Now my unit tests are very clean and easy to setup.    Using MbUnit as my unit test framework, here is a unit tests that tests the reset password functionality.

   1: [Test]
   2: public void ResetPasswordQuestion_Should_Send_Email_On_Success()
   3: {
   4:     var newpassword = "newpassword";
   5:     MyMocks.MockMembershipProvider
   6:          .Expect(p => p.ResetPassword(username, answer))
   7:          .Returns(newpassword);
   8:     MyMocks.MockEmailService
   9:          .Expect(m => m.SendPasswordReset(username, newpassword));
  11:     var ac = TestControllerFactory
  12:                 .GetControllerWithFakeContext<AccountController>("POST");
  14:     var results = ac.ResetPasswordQuestion(username, question, answer);
  15:     //write some asserts in here to make sure things worked
  17:     //verify all mocks
  18:     MyMocks.MockMembershipProvider.VerifyAll();
  19:     MyMocks.MockEmailService.VerifyAll();
  20: }

Line #5: I mock the ResetPassword call on the membership provider and tell it to return the new password

Line #8: I mock the SendPasswordReset method on the email service

Line #11: Get an instance of AccountController from the Ninject Kernel

I just write some code to make sure the expected results took place and that my mocks were properly exercised and that’s pretty much it.  No need to have an SMTP server working to test this, no need to have a database, no need to have an authentication method, no need to implement the interfaces or write dummy methods.

I am like a kid in a candy store with all these things: mocking, dependency injection, inversion of control, unit testing…  I am loving it.

So what do you think?  Is this a good way to go about it?  Is there a better way and what is it?

The Best JavaScript Library

I am in the process of creating a new web application using asp.net mvc and I am trying to choose the best JavaScript library to use.  I am pretty much sure that I am going to go with jQuery but nonetheless I wanted to review the libraries out there.  One reason is that I am writing a book and I want to be able to justify to the readers why I am going with jQuery and not the others.

What do I want from my JavaScript Library?

I want it to be easy (I am not a JavaScript expert)
I want it to be small
I want it to be fast
I want it to be extensible
I want good documentation and/or community support
I want good/easy AJAX support
I want it to be asp.net-friendly
I also want it to be testable (I am using TDD for this project/book)
Open Source would be nice but not required

What are my options?

jQuery – http://jquery.com/
Microsoft AJAX – http://www.asp.net/ajax/
Dojo – http://dojotoolkit.org/
Prototype – http://www.prototypejs.org/
YUI – http://developer.yahoo.com/yui/

This is a shortlist but if you want a more exhaustive, read this.  I only picked these, for the simple reasons that I have heard of them and are somewhat known by the community.

3 days later

It’s been 3 days since I started this post and I have spent all that time playing around with these libraries…  I have gone back and forth in my opinion on which library to use.  I love jQuery’s selectors, ease of use and community support.  Porototype is also very popular and somewhat similar to jQuery; but I would take jQuery over Prototype for the simple reason that I like jQuery.  YUI (Yahoo! UI) library is beautiful looking and very comprehensive.



  1. Ease to learn and use
  2. Beautiful syntax (the least typing)
  3. Great community support and lots of fans
  4. Decent Documentation
  5. I already own the book
  6. QUnit test framework (http://docs.jquery.com/QUnit)


  1. UI isn’t that great
  2. Library is not as full-featured without plugins
  3. Plugins are somewhat inconsistent in quality depending on the author



  1. Good documentation
  2. Good community support
  3. Lots of books
    1. Practical Prototype and script-aculo.us
    2. Prototype and script.aculo.us: You Never Knew JavaScript Could Do This!
    3. and many more…
  4. Great UI with the add-on script.aculo.us (http://script.aculo.us/)


  1. Couldn’t find a testing framework (but I didn’t look too hard)
  2. For some purely emotional reason, I prefer jQuery



  1. Great UI components and styles
  2. The best documented library out there, hands down.
  3. Distributed hosting of JS files – the script files will be downloaded from Yahoo server, so when my site becomes a mega-hit, it will scale better.
  4. Great test framework and test runner – check these demos
  5. The most complete library
  6. PDF cheat sheets for every component


  1. Very verbose – not as elegant as jQuery, but that’s not too hard to fix e.g. I can assign YAHOO.util.Event to a variable $E and use $E as the shorthand.

The rest

I got tired of all the research and decided to wrap it up, so I glanced over Microsoft AJAX and Dojo and realized that there isn’t enough there to justify more research.

The winner…

When I started this post, I was pretty certain my final choice will be jQuery.  Then I started playing with Prototype and it looked really good, which kind of opened my eyes to the need to be open minded and objective.  This lead to a more objective look at YUI and the conclusion to use YUI.  I was very impressed with YUI’s look & feel, extensive documentation, testing framework and the icing on the cake was the free hosting of the JavaScript libraries.  This was a really tough decision because I still love jQuery the best.

[poll id=”2″]

Unit Test Private Methods in Visual Studio

I am working on a feature that will let me import twitter messages to yonkly and wanted to write a test for it.  The method is private and I couldn’t get the unit test to see it.  I also didn’t want to use the private accessor class generate by Visual Studio because I was mocking some functionality in the actual class and didn’t really fell like re-mocking it on the private accessor.

So, after several minutes of googling, I found several solutions that I didn’t like.  John Hann uses reflection to test private methods.  Tim Stall has a similar solution at the code project.  Andrew Stopford suggested that I don’t test private methods and use code coverage to make sure that they are being exercised.  I was about to use the methods suggested by John Hann and Tim Stall to test my private methods, but then I accidentally (thanks to IntelliSense) discovered PrivateObject.

The PrivateObject class is part of the Team Test API.

Allows test code to call methods and properties on the code under test that would be inaccessible because they are not public.
from msdn

It turned out to be pretty easy to test private methods and the code looked like this:

var myController = new TwitterController();
var po = new PrivateObject(myController);
var page = 1;
var count = 25;
po.Invoke("ImportTweets", new object[] { page, count });


The code above will call the private method ImportTweets and pass it two integer parameters.  This is the equivalent of calling

myController.ImportTweets( page, count);


Note that this is essentially what John Hann and Tim Stall suggested but why use extra code when PrivateObject is already available for you.

Unit Test Linq to Sql in ASP.Net MVC with Moq

I have just spent the entire day playing with Moq to unit test an asp.net mvc application I am working with. All I wanted to do is test a “create” method that simply adds a record to the database. So here it goes.

1. I created a Mock Http context to be used by my controller. I modified the Moq version of the MvcMockHelpers class from Scott Hanselman and added two more methods to mock an authenticated user

public static HttpContextBase FakeAuthenticatedHttpContext()
var context = new Mock<HttpContextBase>();
var request = new Mock<HttpRequestBase>();
var response = new Mock<HttpResponseBase>();
var session = new Mock<HttpSessionStateBase>();
var server = new Mock<HttpServerUtilityBase>();
var user = new Mock<IPrincipal>();
var identity = new Mock<IIdentity>();

context.Expect(ctx => ctx.Request).Returns(request.Object);
context.Expect(ctx => ctx.Response).Returns(response.Object);
context.Expect(ctx => ctx.Session).Returns(session.Object);
context.Expect(ctx => ctx.Server).Returns(server.Object);
context.Expect(ctx => ctx.User).Returns(user.Object);
user.Expect(ctx => ctx.Identity).Returns(identity.Object);
identity.Expect(id => id.IsAuthenticated).Returns(true);
identity.Expect(id => id.Name).Returns("test"); 
    return context.Object;
public static void
SetFakeAuthenticatedControllerContext(this Controller controller)
var httpContext = FakeAuthenticatedHttpContext();
ControllerContext context =                  
new ControllerContext(
new RequestContext(httpContext,
new RouteData()), controller);
controller.ControllerContext = context;

Note that the identity.Name returns “test” which is the username of an existing user in the database. If I don’t do that then the MembershipProvider.GetUser method will fail.

2. I added a couple of properties to my test class (MessageControllerTest) to make it easy for me to access the controller and view engine in all the test methods

private FakeViewEngine _fakeViewEngine;
public FakeViewEngine FakeViewEngine
if (_fakeViewEngine == null)

              _fakeViewEngine = new FakeViewEngine();
return _fakeViewEngine;

private MessageController authenticatedController;
private MessageController AuthenticatedController
if (authenticatedController == null)
authenticatedController = new MessageController();
authenticatedController.ViewEngine = FakeViewEngine;
return authenticatedController;

3. I created my test method which is going to call a Create method in my MessageController and pass it a string.

public void Create_Message_Test()
AuthenticatedController.Create("This is a test message");

    Assert.AreEqual("Json", FakeViewEngine.ViewContext.ViewName);




using (MyDataContext dc = new MyDataContext())
var query =
m => m.MessageId ==

//verify it was added to the database
        Assert.AreEqual(1, query.Count());

//delete it

//verify it was delete
        Assert.AreEqual(0, query.Count());

Note that in the verification block, I verify:

  1. The view being rendered
  2. The returned type of the ViewData
  3. Properties on the ViewData

Then I clean up the created message by deleting it from the database.


You must add your connection strings and membership definition in an app.config file in your test project. If you don’t then the default consrtuctor of your DataContext will fail to run because it looks for the connection string in the config file.

I am still wrapping my head around the concept of mocking, so any tips or advice will be appreciated.

Here are some good resources that I found during my struggle to get this to work.

ASP.NET MVC Resources

  1. ASP.NET MVC Framework – Part 2: Testing
  2. ASP.NET MVC Session at Mix08, TDD and MvcMockHelpers

LINQ to SQL Resources

  1. Being Ignorant with LINQ to SQL

Testing and Mocking Resources

  1. Moq: Linq, Lambdas and Predicates applied to Mock Objects
  2. Moq
  3. Rhino Mocks
  4. TDD: Test-Driven Development with Visual Studio 2008 Unit Tests