Web客户端UploadStringCompleted事件不会被调用(Webclient Uploa

2019-09-26 13:39发布

我在写单元测试的一些我们开发的Web服务。 我有一个[TestMethod的]该职位的web服务作为休息。 伟大的作品但它不触发我创建的事件处理方法。 经过调试,我注意到,在执行TestMethod的后事件处理程序越来越除尘器。 它去testcleanup。

有没有人遇到这个问题? 下面的代码

 [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");
        }
    }

Answer 1:

问题是在于UploadStringAsync返回void(也就是说,它的发射后不管),并没有本质上让你检测完成。

有一对夫妇的选择。 第一个选项(这是一个我建议)是使用HttpClient的替代和使用PostAsync方法-你可以await 。 在这种情况下,我会做这样的事情:

[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));
    }
}

另一种选择是改变你的完整事件处理信号返回到您的测试上载完成,并在您的测试,等待事件发生。 例如:

[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();
}


Answer 2:

除了上述问题的答案的帖子,我也加入到支持httpwebresponse所以我不必等待事件的方法。

public static AuthTokenResponse GetUserToken(string username, string password)
        {
            string _jsonstringparams =
                String.Format("{{ \"Password\": \"{0}\", \"UserId\": \"{1}\"}}", password, username);
            string _webservicesurl = ConfigurationManager.AppSettings["WebservicesUrl"];
            HttpWebRequest _requestclient = (HttpWebRequest)WebRequest.Create(String.Format("{0}?format=Json", _webservicesurl));
            _requestclient.ContentType = "application/json";
            _requestclient.Method = "POST";
            using (var streamWriter = new StreamWriter(_requestclient.GetRequestStream()))
            {
                streamWriter.Write(_jsonstringparams);
                streamWriter.Flush();
                streamWriter.Close();
                var httpResponse = (HttpWebResponse)_requestclient.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    _responsecontent = streamReader.ReadToEnd();
                }
                AuthTokenResponse _clienttoken = JsonConvert.DeserializeObject<AuthTokenResponse>(_responsecontent);
                return _clienttoken;
            }
        }


文章来源: Webclient UploadStringCompleted event not being called
标签: c# webclient