未调用 Webclient UploadStringCompleted 事件 [英] Webclient UploadStringCompleted event not being called

查看:22
本文介绍了未调用 Webclient UploadStringCompleted 事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我们开发的一些网络服务编写单元测试.我有一个 [TestMethod] 作为休息发布到网络服务.效果很好,但是它不会触发我创建的事件处理程序方法.通过调试,我注意到在执行 testmethod 后,事件处理程序正在获取排除程序.它进入 testcleanup.

I'm writing unit tests for some of the web services we've developed. I have a [TestMethod] that posts to a webservice as rest. Works great however it doesn't trigger the eventhandler method that I created. Through debugging, I've noticed that the eventhandler is getting excluder after the testmethod is executed. It goes to testcleanup.

有人遇到过这个问题吗?这是代码

Has anyone encountered this problem? Here's the code

 [TestMethod,TestCategory("WebServices")]
        public void ValidateWebServiceGetUserAuthToken()
        {
            string _jsonstringparams =
                "{ \"Password\": \"xxx\", \"UserId\": \"xxxx\"}";
            using (var _requestclient = new WebClient())
            {
                _requestclient.UploadStringCompleted += _requestclient_UploadStringCompleted;
                var _uri = String.Format("{0}?format=Json", _webservicesurl);
                _requestclient.Headers.Add(HttpRequestHeader.ContentType, "application/json");
                _requestclient.UploadStringAsync(new Uri(_uri), "POST", _jsonstringparams);
            }
    }

    void _requestclient_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
    {
        if (e.Result != null)
        { 
            var _responsecontent = e.Result.ToString();
            Console.WriteLine(_responsecontent);
        }
        else 
        {
            Assert.IsNotNull(e.Error.Message, "Test Case Failed");
        }
    }

推荐答案

问题是 UploadStringAsync 返回 void(即它是即发即忘)并且本质上不会让您检测完成.

The problem is is that UploadStringAsync returns void (i.e. it's fire and forget) and doesn't inherently let you detect completion.

有几个选项.第一个选项(这是我推荐的选项)是改用 HttpClient 并使用 PostAsync 方法——您可以await.在这种情况下,我会做这样的事情:

There's a couple of options. The first option (which is the one I'd recommend) is to use HttpClient instead and use the PostAsync method--which you can await. In which case, I'd do something like this:

[TestMethod, TestCategory("WebServices")]
public async Task ValidateWebServiceGetUserAuthToken()
{
    string _jsonstringparams =
        "{ \"Password\": \"xxx\", \"UserId\": \"xxxx\"}";
    using (var httpClient = new HttpClient())
    {
        var _uri = String.Format("{0}?format=Json", _webservicesurl);
        var stringContent = new StringContent(_jsonstringparams);
        stringContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); 
        HttpResponseMessage response = await httpClient.PostAsync(_uri, stringContent);
        // Or whatever status code this service response with
        Assert.AreEqual(HttpStatusCode.Accepted, response.StatusCode);
        var responseText = await response.Content.ReadAsStringAsync();
        // TODO: something more specific to your needs
        Assert.IsTrue(!string.IsNullOrWhiteSpace(responseText));
    }
}

另一个选项是更改您的完整事件处理程序,以向您的测试发出上传已完成的信号,并在您的测试中等待事件发生.例如:

The other option is to change your complete event handler to signal back to your test that the upload is completed and in your test, wait for the event to occur. For example:

[TestMethod, TestCategory("WebServices")]
public void ValidateWebServiceGetUserAuthToken()
{
    string _jsonstringparams =
        "{ \"Password\": \"xxx\", \"UserId\": \"xxxx\"}";
    using (var _requestclient = new WebClient())
    {
        _requestclient.UploadStringCompleted += _requestclient_UploadStringCompleted;
        var _uri = String.Format("{0}?format=Json", _webservicesurl);
        _requestclient.Headers.Add(HttpRequestHeader.ContentType, "application/json");
        _requestclient.UploadStringAsync(new Uri(_uri), "POST", _jsonstringparams);
        completedEvent.WaitOne();
    }
}

private ManualResetEvent completedEvent = new ManualResetEvent(false);
void _requestclient_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
    if (e.Result != null)
    {
        var _responsecontent = e.Result.ToString();
        Console.WriteLine(_responsecontent);
    }
    else
    {
        Assert.IsNotNull(e.Error.Message, "Test Case Failed");
    }
    completedEvent.Set();
}

这篇关于未调用 Webclient UploadStringCompleted 事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆