简体   繁体   English

模拟服务中的方法进行单元测试

[英]Mock a method in Service for unit test

I am working on a unit test, that is how I mock:我正在进行单元测试,这就是我模拟的方式:

  mockProxy.Setup(s => s.GetPayment(getPaymentRequest)).ReturnsAsync(getPaymentResponse);
  var sut = new FromService.Service(mockProxy.Object, mockTemplateService.Object, mockAppSettings, mockAgentRepository.Object);
        // Act
        var getBrandingResponse = await sut.GetDeliver(request);

this is my GetDeliver method in service:这是我在服务中的 GetDeliver 方法:

 public async Task<GetDeliverResponse> GetDeliver(GetDeliverRequest request)
    {
        byte[] content = null;
        var request = new FromProxy.GetPaymentRequest()
        {
            .....
        };

        var myresponse = await proxy.GetPayment(request);

My problem is that although I have mocked the GetPatment method and when I debug request has value but myresponse is null, that is why the test is breaking where ever after that use the myresponse.我的问题是,虽然我已经模拟了 GetPatment 方法,并且当我调试请求有值但 myresponse 为空时,这就是为什么测试在使用 myresponse 之后中断的原因。 How I can mock so myresponse bring some value?我如何模拟以便我的响应带来一些价值?

To get your mock to trigger in the code being tested, replace getPaymentRequest in the setup with It.IsAny<PaymentRequest>()为了让您的模拟代码中的触发器被测试,更换getPaymentRequest与设置It.IsAny<PaymentRequest>()
(Assuming your request class is called PaymentRequest , if not, replace PaymentRequest with the actual class name.) (假设您的请求类名为PaymentRequest ,如果不是, PaymentRequest用实际类名替换PaymentRequest 。)

Where you are saying你说的地方
mockProxy.Setup(s => s.GetPayment(getPaymentRequest)).ReturnsAsync(getPaymentResponse); the getPaymentRequest is a reference to a specific instance of the PaymentRequest class, but that instance is not the one that will be passed to your mock at runtime, the result of new FromProxy.GetPaymentRequest() is what will get passed. getPaymentRequest是对PaymentRequest类的特定实例的PaymentRequest ,但该实例不是在运行时传递给模拟的实例, new FromProxy.GetPaymentRequest()的结果将被传递。 You want to use code that maps to anything of that class, not just the one instance you are currently mapping to.您希望使用映射到该类的任何内容的代码,而不仅仅是您当前映射到的一个实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM