未调用Webclient UploadStringCompleted事件

时间:2014-10-02 18:24:29

标签: c# webclient

我正在为我们开发的一些Web服务编写单元测试。我有一个[TestMethod]作为休息发布到web服务。工作得很好,但它不会触发我创建的eventhandler方法。通过调试,我注意到在执行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");
        }
    }

2 个答案:

答案 0 :(得分:0)

问题在于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();
}

答案 1 :(得分:0)

除了上面的答案帖子,我还添加了一种支持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;
            }
        }