有没有一种方法可以在此代码行中模拟_currencyRepository?

时间:2019-09-13 13:10:37

标签: c# unit-testing moq

我正在尝试使用MOQ框架对类进行单元测试。该类中的public方法的行如下所示。

看着那条线,我正在尝试模拟_currencyRepository,但不知道该怎么做。考虑到它有一个像p => new { p.Id, p.Code }这样的参数。

在分析代码时,看来这是一种输出P的方法-我相信是匿名方法。

var currencies = await _currencyRepository.GetsAs(p => new { p.Id, p.Code }, p => p.Id == sellCurrencyId || p.Id == buyCurrencyId);

将鼠标悬停在var上以了解获取返回类型的信息,tootip显示IEnumerable<'a> currencies. Anonymous types: 'a is new{Guid Id, string code}

..和GetAs的定义是:

public async Task<IEnumerable<TOutput>> GetsAs<TOutput>(Expression<Func<TEntity, TOutput>> projector,
                                               Expression<Func<TEntity, bool>> spec = null,
                                               Func<IQueryable<TEntity>, IQueryable<TEntity>> preFilter = null,
                                               params Func<IQueryable<TEntity>, IQueryable<TEntity>>[] postFilters)
        {
            if (projector == null)
            {
                throw new ArgumentNullException("projector");
            }

            return await FindCore(true, spec, preFilter, postFilters).Select(projector).ToListAsync();
        }

GetAs()还是通用类GenericRepository中的成员/方法-其类定义为:

    public class GenericRepository<TContext, TEntity> : IGenericRepository<TEntity>
        where TEntity : BaseEntity
        where TContext : DbContext
    {
        protected readonly TContext DbContext;
        public GenericRepository(TContext dbContext)
        {
            DbContext = dbContext;
        }

      //followed by method definitions including GetAs
}

上面的类从通用接口IGenericRepository<TEntity>继承,该接口定义为:

    public interface IGenericRepository<TEntity>
        where TEntity : class
    {
        //list of methods including GetAs
         Task<IEnumerable<TOutput>> GetsAs<TOutput>(Expression<Func<TEntity, TOutput>> projector,
            Expression<Func<TEntity, bool>> spec = null,
            Func<IQueryable<TEntity>, IQueryable<TEntity>> preFilter = null,
            params Func<IQueryable<TEntity>, IQueryable<TEntity>>[] postFilters);

... BaseEntity只是具有属性的类:

    public class BaseEntity
    {
        public BaseEntity()
        {
            Id = Guid.NewGuid();
            CreatedDate = DateTime.Now;
        }
        public Guid Id { get; set; }
        public DateTime CreatedDate { get; set; }
        public DateTime? UpdatedDate { get; set; }
        public Guid? CreatedBy { get; set; }
        public Guid? UpdateddBy { get; set; }

    }

我已经有了要返回的货币列表,但参数有误。不确定使用什么参数匹配器(我知道参数匹配器是NSubstitute talk。不确定在Moq中是否被称为相同参数)

我尝试了很多事情。以下是其中之一:

            var mockCurrencies3 = new[] { new { Id = buyCurrencyId, Code = "EUR" }, new { Id = sellCurrencyId, Code = "GBP" } };
            MockCurrencyRepository.Setup(x => x.GetsAs(
               It.IsAny<Expression<Func<Currency, (Guid, string)>>>(),
               It.IsAny<Expression<Func<Currency, bool>>>(),
               It.IsAny<Func<IQueryable<Currency>, IQueryable<Currency>>>()))
               .Returns(Task.FromResult(mockCurrencies3.AsEnumerable()));

尝试上述操作无效,因为生产代码中未返回mockCurrencies3值。我什么也没回来。

1 个答案:

答案 0 :(得分:1)

使用提供的信息,我能够创建通用方法来设置所需的行为

[TestClass]
public class MyTestClass {
    [TestMethod]
    public async Task  Should_Mock_Generic() {

        Guid buyCurrencyId = Guid.NewGuid();
        Guid sellCurrencyId = Guid.NewGuid();

        var mockCurrencies3 = new[] { new { Id = buyCurrencyId, Code = "EUR" }, new { Id = sellCurrencyId, Code = "GBP" } };

        var mock = new Mock<IGenericRepository<Currency>>();
        SetupGetAs(mock, mockCurrencies3);

        var _currencyRepository = mock.Object;

        var currencies = await _currencyRepository.GetsAs(p => new { p.Id, p.Code }, p => p.Id == sellCurrencyId || p.Id == buyCurrencyId);

        currencies.Should().NotBeNullOrEmpty();
    }

    Mock<IGenericRepository<TEntity>> SetupGetAs<TEntity, TOutput>(Mock<IGenericRepository<TEntity>> mock, IEnumerable<TOutput> source)
        where TEntity : class {
        mock.Setup(x => x.GetsAs(
          It.IsAny<Expression<Func<TEntity, TOutput>>>(),
          It.IsAny<Expression<Func<TEntity, bool>>>(),
          It.IsAny<Func<IQueryable<TEntity>, IQueryable<TEntity>>>())
       )
       .ReturnsAsync(source);

        return mock;
    }

}