使用可移植类库进行异步单元测试

本文关键字:异步 单元测试 类库 可移植 | 更新日期: 2023-09-27 18:01:20

我有一个可移植的类库,需要至少针对。net 4.5和Silverlight 5。我遇到了一个问题,试图在VS 2012中编写MSTest单元测试,因为我的库不使用新的async/await范式。我可以测试一下这个方法吗?

public static void Get(string uri, string acceptHeader, Action<string> callback)
{
    var request = (HttpWebRequest)WebRequest.Create(uri);
    request.Accept = acceptHeader;        
    request.BeginGetResponse(o =>
    {
        var r = o.AsyncState as HttpWebRequest;
        try
        {
            var response = r.EndGetResponse(o);
            using (var sr = new StreamReader(response.GetResponseStream()))
            {
                callback(sr.ReadToEnd());
            }
        }
        catch (Exception ex)
        {
            throw new WebException(string.Format("Unable to access {0}", uri), ex);
        }
    }, request);
}

使用可移植类库进行异步单元测试

首先,我建议您重新考虑async/await。这是未来的潮流。Microsoft.Bcl.Async提供了针对。net 4.5和SL5的可移植库的async支持。

但是如果您不想这样做,您仍然可以使用async单元测试:

[TestMethod]
public async Task Get_RetrievesExpectedString()
{
  var tcs = new TaskCompletionSource<string>();
  var client = new ... // arrange
  client.Get(uri, acceptHeader, result =>
  {
    tcs.SetResult(result);
  });
  var actual = await tcs.Task;
  Assert.AreEqual(expected, actual);
}

如果你愿意,你也可以用"老派":

[TestMethod]
public void Get_RetrievesExpectedString()
{
  var mre = new ManualResetEvent(initialState: false);
  string actual = null;
  var client = new ... // arrange
  client.Get(uri, acceptHeader, result =>
  {
    actual = result;
    mre.Set();
  });
  mre.WaitOne();
  Assert.AreEqual(expected, actual);
}

就是忍不住要重构代码。您可以使用闭包执行以下操作

public static void Get(string uri, string acceptHeader, Action<string> callback)
{
    var request = (HttpWebRequest)WebRequest.Create(uri);
    request.Accept = acceptHeader;        
    request.BeginGetResponse(o =>
    {
        try
        {
            var response = request.EndGetResponse(o);
            using (var sr = new StreamReader(response.GetResponseStream()))
            {
                callback(sr.ReadToEnd());
            }
        }
        catch (Exception ex)
        {
            throw new WebException(string.Format("Unable to access {0}", uri), ex);
        }
    }, null);
}

然而,在一天结束时,你可以只做以下操作

public async static void Get(string uri, string acceptHeader, Action<string> callback)
{
    var request = (HttpWebRequest)WebRequest.Create(uri);
    request.Accept = acceptHeader;        
    var response = await Task.Factory.FromAsync(
                             request.BeginGetRequestStream ,
                             request.EndGetRequestStream ,
                             uri,
                             null);
    using (var sr = new StreamReader(response))
    {
        callback(sr.ReadToEnd());
    }
}

好的,这就是我的做法

void Main()
{
    {...}
    var request = (HttpWebRequest)WebRequest.Create(uri);
    request.Accept = acceptHeader;
    var response = await request.DownloadStringTaskAwait();
    DoSomeStuff(response);
}
// Define other methods and classes here
public static class HttpWebRequestExtension
{
    public async Task<string> DownloadStringTaskAwait(this HttpWebRequest request)
    {
        var response = await Task.Factory.FromAsync<Stream>(
                            request.BeginGetRequestStream,
                            request.EndGetRequestStream,
                            null);
                    using (var sr = new StreamReader(response))
                    {
                         return sr.ReadToEnd();
                    }
            }
}