Модульное тестирование Entity Framework не возвращает 100% покрытие с использованием прокладок и подделок?

Я пытаюсь выполнить модульное тестирование репозитория, но происходит то, что когда я его тестирую, я не получаю 100% покрытие, а получаю 0% покрытие кода для этого конкретного метода.

Я хочу протестировать без использования сторонних фреймворков, поэтому я хотел использовать прокладки и подделки.

Вот класс, который я пытаюсь протестировать:

namespace AbstractFactory.Repository
{
    using System.Collections.Generic;
    using System.Data.Entity;
    using System.Linq;

    /// <summary>
    /// This class serves as the structure of the Author repository using a database
    /// </summary>
    public class DbAuthorRepository : IRepository<Author>
    {
        /// <summary>
        /// The context
        /// </summary>
        private AbstractFactoryPatternEntities context;

        /// <summary>
        /// Initializes a new instance of the <see cref="DbAuthorRepository"/> class.
        /// </summary>
        /// <param name="context">The context.</param>
        public DbAuthorRepository(AbstractFactoryPatternEntities context)
        {
            this.context = context;
        }

        /// <summary>
        /// Adds the specified author.
        /// </summary>
        /// <param name="author">The author.</param>
        public void Add(Author author)
        {
            this.context.Authors.Add(author);
        }

        /// <summary>
        /// Removes the specified author.
        /// </summary>
        /// <param name="author">The author.</param>
        public void Remove(Author author)
        {
            this.context.Authors.Remove(author);
        }

        /// <summary>
        /// Saves this instance.
        /// </summary>
        public void Save()
        {
            this.context.SaveChanges();
        }

        /// <summary>
        /// Gets all.
        /// </summary>
        /// <returns>
        /// returns a list of all the authors
        /// </returns>
        public IEnumerable<Author> GetAll()
        {
            List<Author> result = this.context.Authors.ToList();

            return result;
        }

        /// <summary>
        /// Gets the by id.
        /// </summary>
        /// <param name="id">The id.</param>
        /// <returns>
        /// returns an entity
        /// </returns>
        public Author GetById(int id)
        {
            Author result = this.context.Authors.Find(id);
            ////this.context.Authors.Single(a => a.AuthorId == id);

            return result;
        }
    }
}

Вот тестовый класс:

[TestClass]
    public class DbAuthorRepositoryTest
    {
        private ShimAbstractFactoryPatternEntities shimContext;

        private ShimDbSet<Author> shimAuthors;

        private List<Author> listAuthors;

        private DbAuthorRepository repository;

        private void SetupShims()
        {
            this.shimContext = new ShimAbstractFactoryPatternEntities(new AbstractFactoryPatternEntities());

            this.listAuthors = new List<Author>
            {
                new Author { AuthorId = 2, FirstName = "Test2", LastName = "Test2" },
                new Author { AuthorId = 3, FirstName = "Test3", LastName = "Test3" },
                new Author { AuthorId = 4, FirstName = "Test4", LastName = "Test4" }
            };

            this.shimAuthors = new ShimDbSet<Author>();

            this.shimAuthors.Bind(this.listAuthors.AsQueryable());

            ShimAbstractFactoryPatternEntities.AllInstances.AuthorsGet = (a) => { return shimAuthors; };

            ShimDbAuthorRepository.AllInstances.GetAll = (a) => { return this.shimContext.Instance.Authors.ToList(); };

            //return this.shimContext.Instance.Authors.ToList();

            //return this.shimAuthors.Instance.ToList() as IEnumerable<Author>;

            //ShimDbSet<Author>.AllInstances.FindObjectArray = (a, b) => { a.ToList(); return shimAuthors.Instance.Contains(b) ; };
        }

        private void SetupRepository()
        {
            this.SetupShims();

            this.repository = new DbAuthorRepository(new AbstractFactoryPatternEntities());
        }

Вот метод проверки:

[TestMethod]
    public void GetAll_MethodIsCalled_RepositoryReturnsCorrectNumberOfAuthorsInTheDbSet()
    {
        using(ShimsContext.Create())
        {
            this.SetupRepository();
            var authorsCount = this.repository.GetAll().Count();
            Assert.AreEqual(authorsCount,3);
        }
    }

Я получаю 0% покрытия кода в методе GetAll, как мне получить его до 100% и почему он получает 0%?


person Randel Ramirez    schedule 01.06.2013    source источник


Ответы (1)


Конечно да, ваш Шим полностью заменил функциональность, поэтому вы не видите покрытия. Поскольку вы уже убедились, что context.Authors переопределен, почему вы все еще переопределяете метод GetAll, который не зависит ни от чего, что вы еще не переопределили?

person jessehouwing    schedule 01.06.2013
comment
Спасибо, теперь я получаю 100% - person Randel Ramirez; 02.06.2013