如何在Xunit测试中模拟存储库并解析服务

时间:2018-09-15 12:13:38

标签: unit-testing mocking repository asp.net-core-2.0

我的WebAPI的流程是:

控制器(DI服务)->服务(DI存储库)->存储库(DI UnitOfWork)

现在我想在控制器中测试一个方法,并验证是否调用了存储库中的一个方法!

控制器:

    public KitController(
    IKitService _kitService)
    {
        kitService = _kitService;
    }

    [HttpPost]
    [Route("[action]")]
    public async Task<IActionResult> AddOrUpdateKit([FromBody]KitViewModel model)
    {
        try
        {
            var entity = await kitService.AddOrUpdateKit(model);
            return Ok(entity);
        }
        catch (Exception ex)
        {
            return BadRequest(ex.Message);
        }
    }

服务

    private readonly IKitRepository kitRepository;
    public KitService(IKitRepository _kitRepository)
    {
        kitRepository = _kitRepository;
    }
 public async Task<Kit> AddOrUpdateKit(KitViewModel model)
    {
        var entity = kitRepository.KitFirstOrDefault(q => q.KitId == model.KitId);
        if (entity == null)
        {
            await kitRepository.AddKit(new LabDomainModels.Lab.Kit()
            {
                KitName = model.KitName,
                ActivationDate = model.ActivationDate,
                ExpirationDate = model.ExpirationDate,
                Brand = model.Brand
            });
        }
        else
        {
            entity.KitName = model.KitName;
            entity.ActivationDate = model.ActivationDate;
            entity.ExpirationDate = model.ExpirationDate;
            entity.Brand = model.Brand;
            kitRepository.UpdateKit(entity);
        }
        return entity;
    }

我想验证是否调用kitRepository.AddKit(...)

我应该如何设置kitRepository的模拟?

更新:

我认为我必须单独测试服务层!不是来自控制器?

0 个答案:

没有答案