在构造函数中接受unitOfWork的模拟服务



我尝试在我的业务逻辑上编写单元测试。

我现在拥有的:

private Mock<IRepository<Theme>> _mockRepository;
    private IBaseService<Theme> _service;
    private Mock<IAdminDataContext> _mockDataContext;
    private List<Theme> _listTheme;
    [TestInitialize]
    public void Initialize()
    {
        _mockRepository = new Mock<IRepository<Theme>>();
        _mockDataContext = new Mock<IAdminDataContext>();
        _service = new ThemeService(_mockDataContext.Object);
        _listTheme = new List<Theme>
                     {
                         new Theme
                         {
                             Id = 1,
                             BgColor = "red",
                             BgImage = "/images/bg1.png",
                             PrimaryColor = "white"
                         },
                         new Theme
                         {
                             Id = 2,
                             BgColor = "green",
                             BgImage = "/images/bg2.png",
                             PrimaryColor = "white"
                         },
                         new Theme
                         {
                             Id = 3,
                             BgColor = "blue",
                             BgImage = "/images/bg3.png",
                             PrimaryColor = "white"
                         }
                     };
    }
    [TestMethod]
    public async Task ThemeGetAll()
    {
        //Arrange
        _mockRepository.Setup(x => x.GetAll()).ReturnsAsync(_listTheme);
        //Act
        List<Theme> results = await _service.GetAll();
        //Assert
        Assert.IsNotNull(results);
        Assert.AreEqual(_listTheme.Count, results.Count);
    }

问题-服务GetAll i得到异常,因为对象是空的。对象-这是存储库。下面是代码细节:

public class BaseService<T> : DomainBaseService, IBaseService<T> where T : BaseEntity
    {
        private readonly IAdminDataContext _dataContext;
        private readonly IRepository<T> _repository;
        public BaseService(IAdminDataContext dataContext)
            : base(dataContext)
        {
            this._dataContext = dataContext;
            this._repository = dataContext.Repository<T>();
        }
        public async Task<List<T>> GetAll()
        {
            return await _repository.GetAll();
        }
    }

正如您所看到的,在服务中,我尝试从unitOfWork (AdminDataContext)获取存储库。但它总是空的。

我应该如何模拟我的服务来测试它的功能?

您从未设置Repository方法来返回模拟存储库。只需在测试的"安排"部分添加以下内容:

_mockDataContext.Setup(x => x.Repository<Theme>()).Returns(_mockRepository.Object);

相关内容

  • 没有找到相关文章

最新更新