2

我是 Moq 的新手,我正在尝试模拟我的存储库。

我正在为其编写单元测试的方法是这样调用存储库:

var paymentState = _agreementPaymentStateRepository.SingleOrDefault(
                         s => s.Agreement.ID == agreementID);

我正在尝试像这样设置我的起订量:

_agreementPaymentStateRepositoryMock
         .Setup(m => m.SingleOrDefault(s => s.AgreementID == 1))
         .Returns(AgreementPayMentStateMocks.GetOne);

我将我的模拟存储库传递给该类,但在调用后 paymentState 变量为空。(我也很乐意跳过指定表达式)。

任何帮助深表感谢。

public PaymentState GetPaymentState(int agreementID)
    {
        try
        {
            _log.AgreementPaymentStateServiceGetStateStart(agreementID);
            var paymentState =
                _agreementPaymentStateRepository.SingleOrDefault(s => s.Agreement.ID == agreementID);

            var stateToGet = MapStateToGet(paymentState);

            _log.AgreementPaymentStateServiceGetStateReturn(agreementID, paymentState.LatestStatus);
            return stateToGet;
        }
        catch (Exception ex)
        {
            _log.ServiceException(ex.ToString());
            throw;
        }
    }

和测试:

 var paymentState = AgreementPayMentStateMocks.GetPayMentState();

        _agreementPaymentStateRepositoryMock.Setup(m => m.SingleOrDefault(s => s.AgreementID == 1)).Returns(AgreementPayMentStateMocks.GetOne);

        var service = new AgreementPaymentStateService(_agreementPaymentStateRepositoryMock.Object, _log.Object);
        var result = service.GetPaymentState(1);

        _agreementPaymentStateRepositoryMock.Verify(m => m.Match(aps => aps.SingleOrDefault(s => s.AgreementID == 1)), Times.Exactly(1));
4

1 回答 1

4

不要在SingleOrDefault调用中使用具体的谓词,而是使用 Moq 的It.IsAny<T>方法:

_agreementPaymentStateRepositoryMock
         .Setup(m => m.SingleOrDefault(It.IsAny<Expression<Func<bool,PaymentState>>>()))
         .Returns(AgreementPayMentStateMocks.GetOne);
于 2013-09-17T20:10:22.623 回答