我对单元测试相当新,我正在尝试为我创建的Web Api控制器创建一个单元测试,它返回一个品牌列表.
我的WebApi控制器Get()
方法如下所示: -
[HttpGet("/api/Brands/Get", Name = "GetBrands")] public async TaskGet() { var brands = await _brandsService.GetAll(null, "Image"); return Json(brands); }
通用服务方法如下所示: -
public async Task> GetAll( Func
, IOrderedQueryable > orderBy = null, string includeProperties = null) { return await _genericRepository.GetAll(orderBy, includeProperties); }
而Generic Repo方法如下所示: -
public async TaskGet (Expression > filter = null, string includeProperties = "", bool noTracking = false) { includeProperties = includeProperties.Trim() ?? string.Empty; IQueryable query = Context.Set (); if (noTracking) { query.AsNoTracking(); } if (filter != null) { query = query.Where(filter); } foreach (var includeProperty in includeProperties.Split (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { query = query.Include(includeProperty); } return await query.SingleOrDefaultAsync(); }
这是有效的,我从DB返回一个品牌列表.
现在我尝试为此创建一个单元测试: -
[SetUp] public void Setup() { Brands = new List{ new Brand { Id = 1, Name = "Adidas", ImageId = 1 }, new Brand { Id = 2, Name = "Nike", ImageId = 2 }, new Brand { Id = 3, Name = "Puma", ImageId = 3 } }; } [Test] public async Task Get_ReturnsAAListOfBrands() { //Arrange var mockService = new Mock >(); mockService.Setup(repo => repo.GetAll(null, null)).Returns(Task.FromResult(Brands)); var controller = new BrandsController(mockService.Object); //Act var result = await controller.Get(); //Assert }
但结果始终为null.我是否正确测试了这个或者是否需要更改单元测试代码以验证模拟服务是否存储了3个项目.
谢谢你的帮助和时间.
您需要配置安装程序以期望测试的特定行为或参数。
在这种情况下,使用It.IsAny
来告诉设置参数的期望值将使测试按预期进行。
假设该GetAll
方法需要两个参数
Func
和string
,则安装程序将根据为这些参数输入的值来配置要执行的操作。
[Test] public async Task Get_ReturnsAAListOfBrands() { //Arrange var mockService = new Mock>(); mockService .Setup(repo => repo.GetAll(It.IsAny , IOrderedQueryable >>(), It.IsAny ())) .ReturnsAsync(Brands); var controller = new BrandsController(mockService.Object); //Act var result = await controller.Get(); //Assert //... }
查看Moq快速入门,以更好地了解如何使用此模拟框架