суббота, 1 сентября 2012 г.

How to implement FakeObjectSet : IObjectSet, about EF 4 unit testing


Hello,

This is actually a great question! FakeObjectSet is not a class included in the framework but just a placeholder name for any fake implementation of the IObjectSet interface. I can share with you right now a very simple version that we often use to implement fake ObjectContext classes for unit tests:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Objects;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Testing
{

    class FakeObjectSetIObjectSet where TEntity : class
    {
        HashSet _data;
        IQueryable _query;

        public FakeObjectSet() : this(new List()) { } 

        public FakeObjectSet(IEnumerable testData)
        {
            _data = new HashSet(testData);
            _query = _data.AsQueryable();
        }

        public void AddObject(TEntity item)
        {
            _data.Add(item);
        }

        public void DeleteObject(TEntity item)
        {
            _data.Remove(item);
        }

        public void Attach(TEntity item)
        {
            _data.Add(item);
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return _data.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return _data.GetEnumerator();
        }

        Type IQueryable.ElementType
        {
            get { return _query.ElementType; }
        }

        Expression IQueryable.Expression
        {
            get { return _query.Expression; }
        }

        IQueryProvider IQueryable.Provider
        {
            get { return _query.Provider; }
        }

    }
}

You will find a brief sample on how to use this in the Sneak Peak blog post I wrote about Testability Improvements in EF 4, here.
Hope this helps

Комментариев нет: