Click here to Skip to main content
12,399,362 members (57,376 online)
Click here to Skip to main content
Add your own
alternative version


30 bookmarked

Mock a database repository using Moq

, 15 Dec 2009 CPOL
Rate this:
Please Sign up or sign in to vote.
The concept of unit testing my code is still fairly new to me and was introduced when I started writing applications with the Microsoft MVC Framework in Visual Studio 2008.

The concept of unit testing my code is still fairly new to me and was introduced when I started writing applications with the Microsoft MVC Framework in Visual Studio 2008. Intimidated somewhat by the Moq library's heavy reliance on lambadas, my early tests used full Mock classes that I would write myself, and which implemented the same interface as my real database repositories. I'd only write the code for the methods I needed, all other methods would simply throw a "NotImplementedException". However, I quickly discovered that the problem with this approach is that whenever a new method was added to the interface, my test project would no longer build (since the new method was not implemented in my mock repository) and I would have to manually add a new method that threw another "NotImplementedException". After doing this for the 5th or 6th time I decided to face my fears and get to grips with using the Moq library instead. Here is a simple example, of how you can mock a database repository class using the Moq library.

Let's assume that your database contains a table called Product, and that either you or Linq, or LLBLGen, or something similar has created the following class to represent that table as an object in your class library:

The Product Class

namespace MoqRepositorySample
    using System;

    public class Product
        public int ProductId { get; set; }

        public string Name { get; set; }

        public string Description { get; set; }

        public double Price { get; set; }

        public DateTime DateCreated { get; set; }

        public DateTime DateModified { get; set; }

Your Product Repository class might implement an interface similar to the following, which offers basic database functionality such as retrieving a product by id, by name, fetching all products, and a save method that would handle inserting and updating products.

The IProductRepository Interface

namespace MoqRepositorySample
    using System.Collections.Generic;
    public interface IProductRepository
        IList<Product> FindAll();
        Product FindByName(string productName);
        Product FindById(int productId);
        bool Save(Product target);

The test class that follows demonstrates how to use Moq to set up a mock Products repository based on the interface above. The unit tests shown here focus primarily on testing the mock repository itself, rather than on testing how your application uses the repository, as they would in the real world.

Microsoft Unit Test Class

namespace TestProject1
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using Moq;

    using MoqRepositorySample;

    /// <span class="code-SummaryComment"><summary>

Download the Sample project and run the tests yourself: (691.96 kb)


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Software Developer (Senior) Salem Web Network
United States United States
Robert Williams has been programming web sites since 1996 and employed as .NET developer since its release in 2002.

You may also be interested in...

Comments and Discussions

QuestionWonderful ! Pin
K K Kodoth7-Aug-15 12:17
memberK K Kodoth7-Aug-15 12:17 
QuestionHow can I use this test with Entity Framework? Pin
Member 107995614-Feb-15 5:46
memberMember 107995614-Feb-15 5:46 
QuestionNo Controllers? Pin
Adnan Salahuddin2-Jan-15 0:54
memberAdnan Salahuddin2-Jan-15 0:54 
GeneralMy vote of 5 Pin
Sturms5-Oct-14 8:24
memberSturms5-Oct-14 8:24 
GeneralMy vote of 5 Pin
blackninja720-Mar-13 14:36
memberblackninja720-Mar-13 14:36 
GeneralFantastic Article Pin
Allen Conway1-Mar-13 10:33
memberAllen Conway1-Mar-13 10:33 
Questionprice datatype! Pin
jalalx5-Apr-12 21:32
memberjalalx5-Apr-12 21:32 
GeneralThat's not a test! Pin
janus00713-Jan-11 9:26
memberjanus00713-Jan-11 9:26 
GeneralRe: That's not a test! Pin
makv200918-Oct-11 0:03
membermakv200918-Oct-11 0:03 
GeneralRe: That's not a test! Pin
Aurimas21-Mar-12 22:31
memberAurimas21-Mar-12 22:31 
GeneralRe: That's not a test! Pin
bnjkukunuri31-Jan-15 4:44
memberbnjkukunuri31-Jan-15 4:44 
GeneralRe: That's not a test! Pin
Aurimas31-Jan-15 5:01
memberAurimas31-Jan-15 5:01 
GeneralRe: That's not a test! Pin
bnjkukunuri31-Jan-15 6:43
memberbnjkukunuri31-Jan-15 6:43 
GeneralRe: That's not a test! Pin
Aurimas31-Jan-15 8:45
memberAurimas31-Jan-15 8:45 
GeneralRhino vs moq Pin
Sohel_Rana18-Dec-09 21:04
memberSohel_Rana18-Dec-09 21:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160721.1 | Last Updated 15 Dec 2009
Article Copyright 2009 by Williarob
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid