c# – 单元测试Web Api控制器

前端之家收集整理的这篇文章主要介绍了c# – 单元测试Web Api控制器前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我对单元测试相当新,我正在尝试为我创建的Web Api控制器创建一个单元测试,它返回一个品牌列表.

我的WebApi控制器Get()方法如下所示: –

[HttpGet("/api/Brands/Get",Name = "GetBrands")]
public async Task<IActionResult> Get()
{
    var brands = await _brandsService.GetAll(null,"Image");
    return Json(brands);
}

通用服务方法如下所示: –

public async Task<List<T>> GetAll(
    Func<IQueryable<T>,IOrderedQueryable<T>> orderBy = null,string includeProperties = null)
{
    return await _genericRepository.GetAll(orderBy,includeProperties);
}

而Generic Repo方法如下: –

public async Task<T> Get<TKey>(Expression<Func<T,bool>> filter = null,string includeProperties = "",bool noTracking = false)

{
    includeProperties = includeProperties.Trim() ?? string.Empty;
    IQueryable<T> query = Context.Set<T>();

    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<Brand>
    {
        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<IGenericService<Brand>>();
    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< T>()告诉设置在参数方面期望什么将允许测试按需流动.

鉴于GetAll方法需要两个参数
Func< IQueryable< T>,IOrderedQueryable< T>>和字符串,安装程序根据为这些参数输入的值配置要执行的操作.

[Test]
public async Task Get_ReturnsAAListOfBrands() {
    //Arrange
    var mockService = new Mock<IGenericService<Brand>>();
    mockService
        .Setup(repo => repo.GetAll(It.IsAny<Func<IQueryable<Brand>,IOrderedQueryable<Brand>>>(),It.IsAny<string>()))
        .ReturnsAsync(Brands);
    var controller = new BrandsController(mockService.Object);

    //Act
    var result = await controller.Get();
    //Assert
    //...
}

查看Moq Quickstart以更好地理解如何使用此模拟框架

原文链接:https://www.f2er.com/csharp/99912.html

猜你在找的C#相关文章