【发布时间】: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());
}
【问题讨论】:
-
使用
It.IsAny参数设置GetSomeDataFromTheWeb并在设置上使用Callback来获取操作并使用您的存根调用它。 github.com/Moq/moq4/wiki/Quickstart#callbacks -
谢谢,这真的很有魅力。
标签: c# unit-testing moq xunit