Unit Testing Entity Framework Repository without a DB

30. March 2011

One of the problems that I have found is that I have trouble separating the data base calls from my unit tests while still covering my repository. We are going to talk about how to get around this, and pick up after this post to avoid some of the prep work.

We First add a Test Project to the solution to house the tests.

image

 

We want to setup a Product Repository so that we can test it but we want to mock the IRepository that it takes to avoid the database call.

var mockRepository = MockRepository.GenerateMock<IRepository>();
mockRepository.Stub(x => x.AsQueryable<Product>()).Return(new List<Product>
                                                                          {
                                                                              new Product()
                                                                                  {
                                                                                      DaysToManufacture = 4
                                                                                  },
                                                                              new Product()
                                                                                  {
                                                                                      DaysToManufacture = 2
                                                                                  }
                                                                          }.AsQueryable());
var target = new ProductRepository(mockRepository);

We setup the return with a value that should get filtered and a value that should not get filtered as to give us a control set. Make sure to call the AsQueryable on the object initialization so that it matches the return type on the repository.

After we have setup the test them we call our Long running products method.

 

//act
var result = target.GetLongRunningProducts();

//assert
Assert.IsTrue(result.Count() == 1);
Assert.AreEqual(4, result.FirstOrDefault().DaysToManufacture);

This test now gives us the ability to test our filters and our logical separation at the repository level without a database. We can leverage this to run integration performance and query tests against the database as well, but that is another post.

 

Source code is here

Data Access, Design Patterns, Entity Framework

Object Repository Extension to the Standard Repository Pattern

10. March 2011

I have found that there are often times that I use the same queries against an object set but I end up writing the same or very similar LINQ statements against my context. This however can be solved by use a object specific repository. Below is the implementation over Entity Framework 4.1 and the AdventureWorks sample.

 

We start with a plain console application and add a EntityContext folder.

image

Then we add new item ADO.NET Entity Data Model – Name it AdventureWorks.edmx. Use the wizard to connect to the local database for AdventureWorks. Then we add another Folder for our Repository Implementations. This is going to follow the patterns discussed in the Repository patterns post and POCO separation posts.

using System;
using System.Data.Objects;
using System.Linq;
using ObjectRepository.EntityContext;

namespace ObjectRepository.Repository
{
    public class EntityFrameworkRepository : IRepository
    {
        private readonly ObjectContext _context;

        public EntityFrameworkRepository(ObjectContext context)
        {
            _context = context;
        }

        public IQueryable<T> AsQueryable<T>() where T : class
        {
            return _context.CreateObjectSet<T>();
        }

        public void SaveChanges()
        {
            _context.SaveChanges();
        }

        public void Delete<T>(T item) where T : class
        {
           _context.DeleteObject(item);
        }

        public void Add<T>(T item) where T : class
        {
            _context.CreateObjectSet<T>().AddObject(item);
        }

        public void Attach<T>(T item) where T : class
        {
            _context.CreateObjectSet<T>().Attach(item);
        }

        public void Detach<T>(T item) where T : class
        {
            _context.Detach(item);
        }
    }
}

This gives us the base to use, and we could use it as is.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ObjectRepository.EntityContext;
using ObjectRepository.Repository;

namespace ObjectRepository
{
    class Program
    {
        static void Main(string[] args)
        {
            IRepository repository = new EntityFrameworkRepository(new AdventureWorksEntities());

            var longRunningProducts = repository.AsQueryable<Product>().Where(x => x.DaysToManufacture > 3);
        }
    }
}

If we have to use the same long running products query a few times it is going to get old typing it and we have no control over the magic “3”. So how about we wrap a Product specific Repository.

using System.Linq;
using ObjectRepository.EntityContext;

namespace ObjectRepository.Repository
{
    public class ProductRepository : IProductRepository
    {
        private readonly IRepository _repository;

        public ProductRepository(IRepository repository)
        {
            _repository = repository;
        }

        public IQueryable<Product> GetLongRunningProducts()
        {
            return _repository.AsQueryable<Product>().Where(x => x.DaysToManufacture > 3);
        }
    }
}

namespace ObjectRepository.Repository
{
    public interface IProductRepository
    {
        IQueryable<Product> GetLongRunningProducts();
    }
}

Then our usage becomes this…

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ObjectRepository.EntityContext;
using ObjectRepository.Repository;

namespace ObjectRepository
{
    class Program
    {
        static void Main(string[] args)
        {
            IRepository repository = new EntityFrameworkRepository(new AdventureWorksEntities());
            IProductRepository productRepository = new ProductRepository(repository);
            var longRunningProducts = productRepository.GetLongRunningProducts();
        }
    }
}

 

Now no matter where you use the long running products you have the same result, no one has to remember the magic “3” and if it changes it only changes once. This will also allow you to wrap the queries in unit test and integration tests for performance but that is another post.

 

Source Code is here

Data Access, Design Patterns, Entity Framework

Callback to the rescue (part 2)

7. December 2010

I came in this morning to the office and had a couple conversations about callback pattern and usage. It bothers me and several others to have if else if chains or switch statements in the usage. It should be far more intuitive. To help make that happen I went through and wrote a quick open source project that allows for a generic call to handle on the callback handler but it routes that to the right method. This should make using callback pattern far simpler and the code mush easier to understand. You simple implement the abstract class and write your handle methods. Those methods are then traversed and used to route callbacks to. Check it out.

 

http://OpenCallback.codeplex.com

 

Enjoy.

Design Patterns

Callback pattern to the rescue

14. October 2010

So if you have ever gotten stuck with an interface that has callbacks you don’t like / don’t want where you are implementing. To save the day is callback pattern.

Imagine the following scenario. The example is logins.

If the user is logged in already just use those credentials;

If the user has a token from another system use those credentials;

If the user is domain authenticated use those credentials;

otherwise ask the user for login their credentials;

This chain can be achieved by composing the handlers so that when it hits the deepest level needed it succeeds and returns.

 

First you define two very straight forward interfaces.

namespace Core.Interfaces
{
    public interface ICallbackHandler
    {
        ICallBack[] Handle(params ICallBack[] callBacks);
    }
}

 

namespace Core.Interfaces
{
    public interface ICallBack
    {
        bool Handled { get; set; }
    }
}

Then you define the callback that you will need. This is a purely data class. No behavior.

using System.Windows.Forms;
using Core.Interfaces;

namespace Infrastructure.CallBacks
{
    public class WarningCallBack : ICallBack
    {
        public readonly string WarningDescription;

        public WarningCallBack(string warningDesc)
        {
            WarningDescription = warningDesc;
        }

        public bool Handled { get; set;}
    }
}

The behavior is going to be brokered to the implementation specific to the client application by the handler.

public class Handler : ICallbackHandler
    {
        public ICallBack[] Handle(params ICallBack[] callBacks)
        {
            List<ICallBack> unhandledCallBacks = new List<ICallBack>();
            foreach (ICallBack callBack in callBacks)
            {
               callBack.Handled = Handle((WarningCallBack)callBack);
                if(!callBack.Handled)

                {
                    unhandledCallBacks.Add(callBack);
                }
            }

            return unhandledCallBacks.ToArray();
        }

        private bool Handle(WarningCallBack warningCallBack)
        {
            MessageBox.Show(warningCallBack.WarningDescription, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return true;
        }

 

By returning unhandled callbacks you can compose these into a cache stack, or a handle stack.

This saved me a lot of time and ugliness in my code this morning. Thanks to David O’Hara and Craig Neuwirt

Design Patterns

Repository and Interface Re-use between Databases

16. August 2010

When using Entity Framework you run into the problem of having either one repository object for each database or having to not use an Inversion of Control due to having to new the Entities Context each time. I have found that this hit on the architecture side is not required.

This is a follow up to the POCO and Context separation post here. It uses that separation to avoid circular references.

Lets start with our Generic Repository and Interface.

public class EntityFrameworkRepository : IRepository
    {
        private ObjectContext _entities;

        public EntityFrameworkRepository(ObjectContext context)
        {
            _entities = context;
        }

        public IQueryable<T> FindAll<T>() where T : class
        {
            return _entities.CreateObjectSet<T>();
        }

        public IQueryable<T> Find<T>(Expression<Func<T, bool>> where) where T : class
        {
            return _entities.CreateObjectSet<T>().Where(where);
        }

        public T Single<T>(Expression<Func<T, bool>> where) where T : class
        {
            return _entities.CreateObjectSet<T>().Where(where).Single();
        }

        public T SingleOrDefault<T>(Expression<Func<T, bool>> where) where T : class
        {
            return _entities.CreateObjectSet<T>().Where(where).SingleOrDefault();
        }

        public T First<T>(Expression<Func<T, bool>> where) where T : class
        {
            return _entities.CreateObjectSet<T>().Where(where).First();
        }

        public T FirstOrDefault<T>(Expression<Func<T, bool>> where) where T : class
        {
            return _entities.CreateObjectSet<T>().Where(where).FirstOrDefault();
        }

        public T Add<T>(T entity) where T : class
        {
            _entities.CreateObjectSet<T>().AddObject(entity);
            _entities.SaveChanges();
            return entity;
        }

        public void Delete<T>(T entity) where T : class
        {
            _entities.DeleteObject(entity);
            _entities.SaveChanges();
        }

        public T Attach<T>(T entity) where T : class
        {
            _entities.AttachTo(entity.GetType().ToString(),entity);
            _entities.SaveChanges();
            return entity;
        }

        public int SaveChanges()
        {
            return _entities.SaveChanges();
        }
    }
public interface IRepository
    {
        IQueryable<T> FindAll<T>() where T : class;
        IQueryable<T> Find<T>(Expression<Func<T,bool>> where) where T : class;
        T Single<T>(Expression<Func<T, bool>> where) where T : class;
        T SingleOrDefault<T>(Expression<Func<T, bool>> where) where T : class;
        T First<T>(Expression<Func<T, bool>> where) where T : class;
        T FirstOrDefault<T>(Expression<Func<T, bool>> where) where T : class;
        T Add<T>(T entity) where T : class;
        void Delete<T>(T entity) where T : class;
        T Attach<T>(T entity) where T : class;
        int SaveChanges();
    }

Notice that we pass in the Object Context. This is what enables us to separate the usage from the declaration. I am going to use Structure Map as it is my preferred IoC but most IoCs implement this functionality.

image

This is in the configuration code block for Structure Map. Notice that the ObjectContext is created to a named instance of the IRepository. The application services are created with the database that they hit. This allows you two things.

1. Re-use of the interfaces and repository objects between databases.

2. Changing the database for a service is now just an IoC Configuration Change.

 

Enjoy.

Design Patterns, Entity Framework

Separating POCO and Context in EF 4.0

16. August 2010

I found that I like the streamlined process of working with Entity Framework. The auto generation of domain class is nice when dealing with Existing databases. I dislike having to put domain classes in Infrastructure or putting data base context in Core.

Using the POCO Entities T4 templates you can separate these.

Download here

Add a new Entity Data Model and Generate from the data base.

image

Then right click the background of the model and add a generated code item.

image

Select the POCO Objects

image 

This will create Two .tt files. One is the POCO Classes and one is the Context. We are going to use the onion architecture for this example. We want to move the context to infrastructure so that our model and POCO classes and model are in core.

image

and

image

To separate the context from the Domain we will need to edit the context template. You do not want to edit the classes generated because this will just get wiped out.

image

image

The edit we have to make is to simply add the namespace of the Domain objects to the using statements, and the path of the EDMX file to the input. I am still hunting a way to keep from hard coding a absolute path to the EDMX but until then this will have to work.

 

Enjoy.

C#, Data Access, Design Patterns, Entity Framework

Comments versus Well written code

16. September 2009

So the conversation started today about a guy leaving our team and needing to knowledge transfer his part of the code base to the other team members. The lead programmer on the project told him to stop working on new development and start commenting his code so that the people coming in after him would understand what he had been doing.

Personally the first thing I do when opening a code base that I am not familiar with is to press CTRL-M, CTRL-O and start looking around. ( CTRL-M, CTRL-O is the default visual studio short cut for minimize all outlining. You get to see method declarations, and that is about it.) This will collapse blocks of comments so that they are not intrusive. I never re-expand them. The idea that you need comments for understanding code to me is a big red flag for bad code. I feel well named variables are much more intuitive to learning a new code base than using comments.

I have never sat down to learn an entire code base at one sitting. I am normally working on a small part or a bug fix and need to find something that is very specific. To that end a well named class/method/property is much more helpful with you use the ?Edit->Find? code parser than having to sort through and search all the comments for the set of information that you need.

Also, I am sure that almost everyone has opened a piece of code that had a form1, or class1 class right? Those names that MS graces us with are not supposed to stay named that. Here is the way you avoid this.

Step 1: Go to add class

Step 2: DON?T CLICK OK!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

Step 3: Look down at the bottom of the dialog and type in something intuitive.

image

Step 4: Go drink something with an umbrella and retire to the happy place of understandable class name land.

To prove my point.

   1:  //This is a class that handles 
   2:  //calculating tax for sales in 
   3:  //several states
   4:  public class class1
   5:  {
   6:          //Calc sales total for a couple states
   7:          //AR - tax 9.5%
   8:          //NM - tax 5.5%
   9:          //TX - tax 8.5%    
  10:          public decimal calc(decimal a, string n)
  11:         {
  12:               //The quick red fox jumped over the lazy brown dog.
  13:               //The quick red fox jumped over the lazy brown dog.
  14:               //The quick red fox jumped over the lazy brown dog.
  15:               //The quick red fox jumped over the lazy brown dog.
  16:               switch(n)
  17:               {
  18:                     case "AR":
  19:                            {
  20:                                  return  a * 1.095;
  21:                             }
  22:                             break;
  23:                      case "TX":
  24:                              {
  25:                                  return a * 1.0875;
  26:                              }
  27:                              break;
  28:                      case "NM":
  29:                             {
  30:                                  return a * 1.055;
  31:                              }
  32:                              break;
  33:                }    
  34:         }
  35:  }

versus my way

   1:  public class MultiStateSalesTaxCalculator
   2:  {
   3:          public decimal ARKANSAS_STATE_SALES_TAX = 0.095;
   4:          public decimal TEXAS_STATE_SALES_TAX = 0.095;
   5:          public decimal NEW_MEXICO_STATE_SALES_TAX = 0.095;
   6:   
   7:          public decimal CalculateSalesTotalWithTaxByState(decimal SubTotal, string stateAbreveation)
   8:         {
   9:               switch(stateAbreveation)
  10:               {
  11:                     case "AR":
  12:                            {
  13:                                  return  SubTotal + ( SubTotal * ARKANSAS_STATE_SALES_TAX)  ;
  14:                             }
  15:                             break;
  16:                      case "TX":
  17:                             {
  18:                                  return SubTotal + ( SubTotal * TEXAS_STATE_SALES_TAX);
  19:                              }
  20:                              break;
  21:                      case "NM":
  22:                             {
  23:                                  return SubTotal + ( SubTotal * NEW_MEXICO_STATE_SALES_TAX);
  24:                              }
  25:                              break;
  26:                }    
  27:         }
  28:  }

.NET, C#, Design Patterns

Generics ? What you should know?

11. September 2009

I have had some interesting conversations over the last week or so about generics. It was brought up out of a MCTS study group and then in the internal DNUG that I lead. so let me break it down.

Without Generics -

I have to setup collections of objects manual and for each type that I want to use. To add, sort, filter, or aggregate this collection takes a lot of code and time. Some things like ArrayList return objects which means all that casting or reflection over head to get into the objects I need.

With Generics -

I have to setup a collection and give it the input types. It handles sorting, filtering, adding, and aggregates through the use of generic Action<T>, Func<T>, or Predicate<T>. I can write sorts and filters and make them generic so that I don?t have to copy/paste change type.

Generics are not the end all and be all but they help a great deal when you are trying not to repeat yourself. I have found that when using generics that the compiler actually spits out the methods with the implemented types in them, which means that generics while great are syntactic sugar, and I have a sweet tooth.

With Linq being based on the use of IEnumerable<T> and the new parallel extensions to .NET 4.0 being able to spread the workload of Action<T> and Task<T> across multiple processors I would tell everyone. Start learning generics. It is easy to use once you wrap your head around it. Like if I wanted to add two numbers of different types I could write this:

public float Add(int one, decimal two)
{
       float item = new float();
       item = float.Parse(one.ToString()) + float.Parse(two.ToString());
       return item;
}

public float Add(decimal one, decimal two)
{
       float item = new float();
       item = float.Parse(one.ToString()) + float.Parse(two.ToString());
       return item;
}

public float Add(int one, int two)
{
       float item = new float();
       item = float.Parse(one.ToString()) + float.Parse(two.ToString());
       return item;
}

public float Add(double one, double two)
{
       float item = new float();
       item = float.Parse(one.ToString()) + float.Parse(two.ToString());
       return item;
}

public float Add(int one, double two)
{
       float item = new float();
       item = float.Parse(one.ToString()) + float.Parse(two.ToString());
       return item;
}

public float Add(double one, decimal two)
{
       float item = new float();
       item = float.Parse(one.ToString()) + float.Parse(two.ToString());
       return item;
}

or I could write this:

public float Add<T, T2>(T one, T2 two)
{
      return float.Parse(one.ToString()) + float.Parse(two.ToString());
}

Which would you prefer?

 

Enjoy, and remember.

Code Like you have to support it.

.NET, C#, Design Patterns

Test Driven Development ? Not for the faint of heart.

10. September 2009

I started coding in C# about a year ago and almost immediately found that once I had completed a project I wanted to go back and streamline and improve it. When time allowed I started trying to do this and found that the code was very hard to verify functionality. I also found that some of my design choices were pretty novice, due to that the code was very hard to enhance. 
I got introduced to the idea of test driven development by a good friend Rob Tennyson. He presented on the topic at the Tyson Foods internal .NET user group. This peaked my interest for two reasons. One, It would allow for avoiding the novice mistakes in design and class layout. Two, it would allow for my code to have automated verification of functionality.
I set out to work TDD into my everyday process and hit several brick walls.
1. You end up making things public for testing that should not be otherwise, or putting test code into the finished product (neither is a workable solution in my book). I am using NUnit and I didn't want to have a reference to a testing package in my production code. Adding a dependency to the production code that other developers will have to deal with was not my idea of a stable codebase.
2. Being a beginner in TDD as well as C# I didn't know what I didn't know so by that lack of code and language knowledge I repeated some novice mistakes in design. Not as many as before but still a few. Some would argue that I gained knowledge and that is why I see those bottlenecks and design issues more clearly and to that my only reply is "yeah prolly".
3. Abstraction is a premium but sometimes too much work. I write a lot of small applications, an editor here, a website there. While I do work to abstract a lot of my code and provide interfaces in the right places for a small application putting in the level of seams needed for proper TDD would be building an elevator in an outhouse.
4. I found it increasingly difficult to find answers in my hunt for TDD utopia. I read several books on the subject and found that I was more often than not provided with contradictory rules to apply, or methods to use. Microsoft's "Test-Driven Development in Microsoft .NET" by James W. Newkirk and Alexei A. Vorontsov gave great baseline examples and presented the basics of TDD very well, however it fails to provide good solid base for TDD in the real world. The application that they base a lot of their examples around ignores some fairly large aspects of the TDD mindset like separation of integration testing and design testing.

With the miles behind me and a TDD utopia still nowhere in sight I have found several good ideas.

1. Kent Beck's TDD by Example is a great resource for TDD on the intermediate to advanced level.

2. Not everything needs to be designed using TDD, some things are just too trivial.

3. TDD is a design pattern, and it should be used as such. If you want automated testing use automated tests, but if you want TDD programs before one line of code is written have a test list and priority assigned to them.

I am working on a TDD project currently with Jay Smith and Rob Tennyson to write a checkers application using only TDD and having no UI or Data Layer. Building Logic first, then the UI, and finally adding a data layer to detail how to handle those real world integration concerns.

Just Remember Code like you have to support it.

C#, .NET, Productivity, Unit Testing, Design Patterns