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

Property Injection in ASP.NET MVC with Ninject

I got a design challenge with asp.net mvc.  I want to keep track of the currently logged in user in the session because I don’t want to hit the database every time I need to get the username or id for a query.  And I have all my controllers inherit from a base controller named BaseController.  So, I added a CurrentUser property to the BaseController and I want it to automagically work without the derived controllers having to do anything.  Here is a class diagram to help clarify:


The CurrentUser Property needs to look something like this:

public User CurrentUser
        var key = "currentuser";
        if (Session[key] == null)
            Session[key] = /*get user from database some how*/;
        return (User) Session[key] ;

This looks simple enough but it is not.  The reason it is not simple is because to get the current user I have to call Membership.Provider.GetUser from the BaseController.  The problem with that is that it creates a dependency on the MembershipProvider class which I don’t want to have, because it will make testing very hard.

One obvious solution was to add the MembershipProvider (which is an abstract class) to the BaseController’s construct and then pass a mocked instance during testing…  The problem with this design is that now my BaseController will be forced to have a parameterized constructor which means that I have to change the code in all the derived controllers to handle that and pass the appropriate instance of MembershipProvider.  Sounds like a code smell.

My solution was to create the MembershipProvider class using my IoC container – in this case, my Ninject Kernel.  This allows me to inject a SqlMembershipProvider in development and runtime and inject a mocked provider in testing.  So the final CurrentUser property looks like this:

public User CurrentUser
        var key = "currentuser";
        if (Session[key] == null)
            var Provider
                = (MembershipProvider)

            Session[key] = AppHelper.CreateUserFromMembershipUser
                            (Provider.GetUser(User.Identity.Name, true));
        return (User) Session[key] ;

If you have been paying attention, you are probably wondering  what is this “Kernel” thing.  Well Kernel is an instance of the Ninject Kernel which itself was injected into the BaseController class like this:

public IKernel Kernel { get; set; }

I could have done this differently.  For example, I could have injected the provider itself using property injection like this:

public MembershipProvider Provider { get; set; }

The only problem is that the provider isn’t needed by all the derived classed and I didn’t want to have a public property in the base class that would hardly be used anywhere else.   On the other hand Kernel could be globally used to instantiate an object.

What do you think?  Is this the way to do it?  Is there a better way?

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.