2
我想測試發送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 – Nkosi
謝謝,這實際上像一個魅力工作。 – zlZimon