【问题标题】:How to unit test a method with a nested action / callback如何使用嵌套操作/回调对方法进行单元测试
【发布时间】:2017-02-16 12:45:05
【问题描述】:

我想测试一个发送 Webrequest 并接收响应的方法。 然而,这不会直接发生,而是使用另一个类来构建请求并发送它。此外,HttpRequest 类对从“建筑类”传递的响应使用回调,它是从我要测试的方法中获取的。

一些代码会使它更清晰。 (简体)

// this is the actual method I want to unit test
public void GetSomeDataFromTheWeb(Action<ResponseData> action, string data)
{
    _webService.GetSomeDataFromTheWeb((req, resp) =>
    {
        // building the response depending on the HttpStatus etc
        action(new ResponseData());
    },data);
}

// this is the "builder method" from the _webService which I am gonna mock in my test
  public void GetSomeDataFromTheWeb(Action<HTTPRequest, HTTPResponse> response, string data)
{
    HTTPRequest request = new HTTPRequest(new Uri(someUrl)), HTTPMethods.Get,
        (req, resp) =>
        {
            response(req, resp);
        });            
    request.Send();
}

我可以创建一个 HttpResponse 它应该看起来的样子,但我不知道如何将它“放入”最后一个方法的 response(req,resp) 调用。

我如何模拟_webService,它从我想用HttpResponse 测试的方法调用正确的回调,我要输入我的单元测试?

基本上是这样的:

[Fact]
public void WebRequestTest()
{
  var httpresponse = ResponseContainer.GetWebRequestResponse();
  var webserviceMock = new Mock<IWebService>();

  //get the response somehow into the mock
  webserviceMock.Setup(w=>w.GetSomeDataFromTheWeb( /*no idea how*/));

  var sut = new MyClassIWantToTest(webserviceMock);

  ResponseData theResult = new ResponseData();
  sut.GetSomeDataFromTheWeb(r=>{theResult = r}, "");

  Assert.Equal(theResult, ResultContainer.WebRequest());
}

【问题讨论】:

标签: c# unit-testing moq xunit


【解决方案1】:

使用It.IsAny 参数设置GetSomeDataFromTheWeb,并使用设置上的Callback 来获取操作并使用您的存根调用它。

https://github.com/Moq/moq4/wiki/Quickstart#callbacks

webserviceMock
    .Setup(w=>w.GetSomeDataFromTheWeb( It.IsAny<Action<HTTPRequest, HTTPResponse>>, It.IsAny<string>))
    .Callback((Action<HTTPRequest, HTTPResponse> response, string data)=>{...});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-21
    • 2021-12-01
    • 2013-11-25
    • 2023-03-06
    • 2021-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多