如何使用嵌套操作/回调单元测试方法
问题描述:
我想测试发送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());
}
答
设置的GetSomeDataFromTheWeb
有It.IsAny
参数和使用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)=>{...});
设置了'GetSomeDataFromTheWeb'用'It.IsAny'参数和使用'Callback'上设置抢行动,并与您的存根调用它。 https://github.com/Moq/moq4/wiki/Quickstart#callbacks – Nkosi
谢谢,这实际上像一个魅力工作。 – zlZimon