Moq验证是否使用任何表达式调用了Method

时间:2013-09-17 20:04:46

标签: c# moq

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

我正在编写单元测试的方法是调用存储库,如下所示:

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

我正试图像这样设置我的moq:

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

我将模拟的存储库传递给类,但调用完成后,paymentState变量为null。 (我会轻易地跳过指定表达式。)

非常感谢任何帮助。

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));

1 个答案:

答案 0 :(得分:4)

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

_agreementPaymentStateRepositoryMock
         .Setup(m => m.SingleOrDefault(It.IsAny<Expression<Func<bool,PaymentState>>>()))
         .Returns(AgreementPayMentStateMocks.GetOne);