mardi 25 août 2015

UnitTesting PatIndex

when unit testing PatIndex of SqlFunctions with a mocked IQueryable object I'm getting the following error:

"This function can only be invoked from LINQ to Entities."

Here is how I initialize my mock repositories:

        protected void InitUnitOfWork<TEntity>(IEnumerable<TEntity> data)
            where TEntity : class
    {
        var dataSet = Substitute.For<IDbSet<TEntity>, IQueryable<TEntity>>().Initialize(data.AsQueryable());
        var query = Substitute.For<IRepositoryQuery<TEntity>>();
        var repository = Substitute.For<IRepository<TEntity>>();

        this.UnitOfWork.Repository<TEntity>().Returns(repository);
        repository.Query().Returns(query);
        query.Include(null).ReturnsForAnyArgs(query);
        query.Filter(null).ReturnsForAnyArgs(query);
        query.Get().Returns(dataSet);
    }

This is the method I'm trying to test:

        public IEnumerable<ContactDto> GetContactsBySearchText(string searchText)
    {
        var companyId = CurrentUser.User.CurrentCompany.Id;

        var contacts = this.GetIQueryableContacts().Where(x => x.CompanyMasterData.Id == companyId);

        if (!string.IsNullOrWhiteSpace(searchText))
        {
            var pattern = SearchQueryParserHelper.ParseString(searchText.Trim());
            contacts = contacts.Where(x => SqlFunctions.PatIndex(pattern, x.Name) > 0
                || SqlFunctions.PatIndex(pattern, x.Code) > 0
                || SqlFunctions.PatIndex(pattern, x.Phone) > 0);
        }

        return Mapper.Map<IQueryable<Contact>, IEnumerable<ContactDto>>(contacts);
    }

I know I can fix this issue by using the database, but how can I mock it correctly?

I'm using NSubstitute as Mocking Framework.

Best regards

Daniel

Aucun commentaire:

Enregistrer un commentaire