我有一个名为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传递给网关服务上的stubbed方法。来自网关服务的响应是该方法返回的响应。但是,由于我正在对我的网关服务方法进行存根的方式,它并不关心传递给它的内容。结果,似乎我无法测试该方法是否正确地将请求对象映射到域对象。
我什么时候可以在这里做,仍然坚持BDD?
答案 0 :(得分:2)
要检查发送到IGatewayService的对象是否正确,可以使用回调来设置对域对象的引用。然后,您可以在该对象的属性上编写断言。
示例:
_mockGatewayService
.Setup(x => x.Process(Moq.It.IsAny<PaymentInfo>())
.Callback<PaymentInfo>(paymentInfo => _paymentInfo = paymentInfo);
答案 1 :(得分: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约束,该约束接受Predicate(要满足的参数测试)。实现CheckPaymentInfo以对预期的PaymentInfo进行断言。
e.g。检查Add是否传递偶数作为参数,
mock.Setup(foo => foo.Add(It.Is<int>(i => i % 2 == 0))).Returns(true);