模拟不返回设置值

Mock is not returning setup value

我在下面使用 Xunit 和 Moq 进行单元测试的方法。

public class PersonService : IPersonService
{
    private readonly IUnitOfWork _unitOfWork;
    private readonly IMapper _mapper;

    public PersonService(IUnitOfWork unitOfWork, IMapper mapper)
    {
        _unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
        _mapper = mapper;
    }

    public async Task<int> PostPersonAsync(PersonModel person)
    {
        int result = 0;

        using (_unitOfWork.Connection)
        {
            try
            {
                _unitOfWork.OpenConnection();

                _unitOfWork.Begin();

                var PersonDto = _mapper.Map<PersonDto>(person);

                result = await _unitOfWork.PersonRepository.PostPersonAsync(PersonDto, _unitOfWork.Transaction);

                _unitOfWork.Commit();

                _unitOfWork.CloseConnection();
            }
            catch (Exception ex)
            {
                _unitOfWork.Rollback();
                throw;
            }
        }
        return result;
    }

}

下面是我的 Xunit 方法:

[Fact]
public void PostPersonAsync_Should_SavePerson()
{
    //Arrange
    var _IDbTransaction = new Mock<IDbTransaction>();
    var _unitOfWorkMock1 = new Mock<IUnitOfWork>();
  
    
    var PersonDto = _mapper.Map<PersonDto>(PersonServiceData.PersonModel);
    int numberofAffectedRows = 5;
    _unitOfWorkMock1.Setup(s => s.OpenConnection());
    _unitOfWorkMock1.Setup(s => s.PersonRepository.PostPersonAsync(PersonDto, _IDbTransaction.Object)).ReturnsAsync(()=>numberofAffectedRows);
    _unitOfWorkMock1.Setup(s => s.CloseConnection());
    
    _target = new PersonService(_unitOfWorkMock1.Object, _mapper);

    //Act
    var result = _target.PostPersonAsync(PersonServiceData.PersonModel).Result;

    //Assert
    Assert.Equal(5, result);
}

我不确定为什么它仍然 return 为零,我的测试用例失败了。

我也试过下面的方法,但我的测试用例仍然失败。

_unitOfWorkMock1.Setup(s => s.PersonRepository.PostPersonAsync(PersonDto, _IDbTransaction.Object)).ReturnsAsync(()=>numberofAffectedRows);

即使在为存储库方法调用设置 return 值之后,它也是 return 零。

试试这个:

_unitOfWorkMock1
    .Setup(s => s.PersonRepository.PostPersonAsync(It.IsAny<PersonDto>(), It.IsAny<IDbTransaction>()))
    .ReturnsAsync(numberofAffectedRows);