搜索的get函数不是给出搜索结果,而是在单元测试时返回所有元素

问题描述 投票:0回答:0

我有一个名为 GetAuthors 的函数,它接受一个表达式来检查给定的字符串是否在作者姓名中。我在单元测试时遇到问题。该函数应该查找包含给定字符串的名称,但我意识到它总是返回列表中的所有内容。我用 G 字母测试它应该会失败但它通过了。我只找到了没有参数的示例,用于获取函数单元测试。我是 web api 中单元测试的新手。我分享下面的代码。

测试功能:

[Test]
    public async Task AuthorHandler_GetAuthors_ReturnsAuthors()
    {
        var handler = new GetAuthorsHandler(_authorRepositoryMock.Object, _mapper);
        var authors = new List<Author> { 
            new Author{Id = 2, Name = "Orhan", Surname = "Pamuk"},
            new Author{Id = 3, Name = "Patti", Surname = "Smith"},
            new Author{Id = 1, Name = "J.R.R.", Surname = "Tolkien"}

        };
        
        string str = "G";
        str=str.Trim().ToUpper();
        _authorRepositoryMock.Setup(r => r.GetAuthors(It.IsAny<Expression<Func<Author, bool>>>()))
            .ReturnsAsync(authors);

        //Act
        var result = await handler.Handle(new GetAuthorsQuery(str), CancellationToken.None);
        
        //Assert
        Assert.AreNotEqual(0, result.Count());

    }

存储库中的 GetAuthors 函数:

public async Task<IEnumerable<Author>> GetAuthors(Expression<Func<Author, bool>> pred = null)
    {
        if (pred == null) return await _context.Authors.Include(a => a.Book).ToListAsync();
        else return await _context.Authors.Where(pred).Include(b => b.Book).ToListAsync();
    }

处理程序:

   public async Task<IEnumerable<AuthorDto>> Handle(GetAuthorsQuery request, CancellationToken cancellationToken)
    {
        IEnumerable<Author> authors;
        if (request.Str != null)
        {
            request.Str = request.Str.Trim().ToUpper();
            authors = await _authorRepository.GetAuthors(x => x.Name.Trim().ToUpper().Contains(request.Str));
        }
        else { authors = await _authorRepository.GetAuthors(null); }
        
        if (authors == null) return null;
        return _mapper.Map<List<AuthorDto>>(authors);
    }
c# unit-testing asp.net-core-webapi nunit web-api-testing
© www.soinside.com 2019 - 2024. All rights reserved.