Unit Testing .NET Application with Moq Framework

Hi guys,

It’s been a while since my last post here. In 2011 however I will try to come back to my routine of posting something new at least once a month. Today, I will share with you the way I’ve been writing tests for my ASP.NET applications using Moq framework.

So let’s start.

Firstly, it’s important to know a little about mocking objects. As the name already suggest, unit tests should verify the behavior of a single unit of your code. For that reason, the code been tested must be isolated from any other dependencies that it has. The simplest example is a business logic test with database manipulation. See the code below

ProductBusiness.cs

ProductBusinessTest.cs

When testing business validation, the programmer does not have to access the database for that. In other words, your code should be isolated from the data layer. To do that while testing, you must create mock object (simulated objects that mimic the behavior of real objects in controlled ways). One way of doing that is using Moq framework. See the code below, now using the Moq framework.

ProductBusinessWithMoqTest.cs

As you can see, now I am able to determine the behavior of my data layer by creating a mock object with a specific behavior. Therefore, I isolated my test from any dependency it had. To know more about Moq framework, you can look at http://code.google.com/p/moq/wiki/QuickStart

In the next post, I will show how I use Moq to test my controller in ASP.NET MVC application.

See you,
Fernando

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s