3

我有一个方法叫做ProcessPayment()我正在通过 BDD 和 mspec 开发。我需要帮助来应对新的挑战。我的用户故事说:

Given a payment processing context,
When payment is processed with valid payment information,
Then it should return a successful gateway response code.

为了设置上下文,我使用 Moq 对网关服务进行存根。

_mockGatewayService = Mock<IGatewayService>();
_mockGatewayService.Setup(x => x.Process(Moq.It.IsAny<PaymentInfo>()).Returns(100);

这是规格:

public class when_payment_is_processed_with_valid_information {

    static WebService _webService;
    static int _responseCode;
    static Mock<IGatewayService> _mockGatewayService;
    static PaymentProcessingRequest _paymentProcessingRequest;

    Establish a_payment_processing_context = () => {

        _mockGatewayService = Mock<IGatewayService>();
        _mockGatewayService
            .Setup(x => x.Process(Moq.It.IsAny<PaymentInfo>())
            .Returns(100);

        _webService = new WebService(_mockGatewayService.Object);

        _paymentProcessingRequest = new PaymentProcessingRequest();
    };

    Because payment_is_processed_with_valid_payment_information = () => 
        _responseCode = _webService.ProcessPayment(_paymentProcessingRequest); 

    It should_return_a_successful_gateway_response_code = () => 
        _responseCode.ShouldEqual(100);

    It should_hit_the_gateway_to_process_the_payment = () => 
        _mockGatewayService.Verify(x => x.Process(Moq.It.IsAny<PaymentInfo>());

}

该方法应采用“PaymentProcessingRequest”对象(不是域 obj),将该 obj 映射到域 obj,并将域 obj 传递给网关服务上的存根方法。网关服务的响应是该方法返回的内容。但是,由于我对网关服务方法进行存根的方式,它并不关心传递给它的内容。结果,似乎我无法测试该方法是否将请求对象正确映射到域对象。

我什么时候可以在这里做并且仍然坚持 BDD?

4

2 回答 2

2

要检查发送到您的 IGatewayService 的对象是否正确,您可以使用回调设置对域对象的引用。然后,您可以在该对象的属性上编写断言。

例子:

_mockGatewayService
            .Setup(x => x.Process(Moq.It.IsAny<PaymentInfo>())
            .Callback<PaymentInfo>(paymentInfo => _paymentInfo = paymentInfo);
于 2010-08-10T21:30:16.650 回答
0

所以据我了解,
您想在 WebService.ProcessPayment 方法中测试映射逻辑;存在输入参数 A 到对象 B 的映射,该对象 B 用作 GateWayService 协作者的输入。

It should_hit_the_gateway_to_process_the_payment = () => 
        _mockGatewayService.Verify(
             x => x.Process( Moq.It.Is<PaymentInfo>( info => CheckPaymentInfo(info) ));

使用 Moq It.Is 约束,它接受一个谓词(满足参数的测试)。实现 CheckPaymentInfo 以针对预期的 PaymentInfo 进行断言。

例如检查 Add 是否传递了偶数作为参数,

 mock.Setup(foo => foo.Add(It.Is<int>(i => i % 2 == 0))).Returns(true); 
于 2010-08-11T05:14:11.233 回答