Welcome!

The .NET Addict's Blog

Kevin Hoffman

Subscribe to Kevin Hoffman: eMailAlertsEmail Alerts
Get Kevin Hoffman via: homepageHomepage mobileMobile rssRSS facebookFacebook twitterTwitter linkedinLinkedIn


Related Topics: Microsoft Developer, Azure Cloud on Ulitzer

Blog Feed Post

Modifying The Default Unit Tests for an ASP.NET MVC Project To Use Moq

This is a very handy feature and definitely helps get you going quickly

When you create a new ASP.NET MVC project, one of the first things that you might notice is that you get an AccountController which takes advantage of the ASP.NET membership provider to allow your site to automatically do forms-based authentication right from the very beginning. This is a very handy feature and definitely helps get you going quickly.

The issue is that when you look at the unit tests for the AccountController, they are positively littered with manually mocked classes. I realize that this is because you don't want to make the default project template rely on a third party mocking library so in this blog post, I'm going to show how you can delete all of the manually implemented mocks for the identity, principal, membership service and forms auth service. The secret is using Moq. Moq is a lightweight mocking framework for .NET that was designed specifically for the .NET Framework 3.5 and LINQ. As such, definining mock expectations and mock return values is all done through lambdas in a ridiculously easy to read syntax, as you'll see below.

First, you want to add a reference to the Moq library. To get Moq, you can go to Moq's Google Code home page . Once you've got the Moq library on your machine, add a reference to it from your unit test project (you did choose to create a unit test project with your new ASP.NET MVC project, didn't you?). With that in place, you can replace the contents of the "GetAccountController()" method with the Moq-enabled one below:

Read the original blog entry...

More Stories By Kevin Hoffman

Kevin Hoffman, editor-in-chief of SYS-CON's iPhone Developer's Journal, has been programming since he was 10 and has written everything from DOS shareware to n-tier, enterprise web applications in VB, C++, Delphi, and C. Hoffman is coauthor of Professional .NET Framework (Wrox Press) and co-author with Robert Foster of Microsoft SharePoint 2007 Development Unleashed. He authors The .NET Addict's Blog at .NET Developer's Journal.