2

我真的可以使用一些帮助来理解为什么这个单元测试失败了。我怀疑这是由于我处理流的方式。我有许多其他测试成功地使用了这种自托管服务器设置,但它们都读取了返回字符串等原语的服务。

这是有问题的测试:

using System.Net.Http;
using System.Threading;
using System.Web.Http.SelfHost;
using AttributeRouting.Web.Http.SelfHost;
using NUnit.Framework;

[TestFixture]
public class StreamControllerTests 
{
    [Test]
    public void Can_get_simple_streaming_service_to_respond()
    {
        using (var config = new HttpSelfHostConfiguration("http://in-memory"))
        {
            config.Routes.MapHttpAttributeRoutes();
            using (var server = new HttpSelfHostServer(config))
            {
                // I get the same behavior if I use HttpClient
                using (var client = new HttpMessageInvoker(server))
                {
                    using (var request = new HttpRequestMessage(HttpMethod.Get, "http://in-memory/stream/notepad"))
                    {
                        using (HttpResponseMessage response = client.SendAsync(request, CancellationToken.None).Result)
                        {
                            Assert.IsNotNull(response.Content);
                            // FAILS, content length is 0
                            Assert.Greater(response.Content.Headers.ContentLength, 0); 
                        }
                    }
                }
            }
        }

这是提供测试的控制器:

using System;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using AttributeRouting.Web.Mvc;
using MyUnitTests.Properties;

[GET("stream/notepad")]
public HttpResponseMessage StreamAnImageFromResources()
{
    var imageStream = new MemoryStream(); // closed when stream content is read
    Resources.a_jpeg_in_resources.Save(imageStream, ImageFormat.Jpeg);
    try
    {                               
        HttpResponseMessage response = Request.CreateResponse();
        // at this point, imageStream contains about 120K bytes
        response.Content = new StreamContent(imageStream); 
        return response;            
    }
    catch (Exception e)
    {
        return Request.CreateErrorResponse(HttpStatusCode.ServiceUnavailable, e);
    }
}
4

1 回答 1

2

我没有看到任何真正的错误,但您的测试比它需要的更复杂。

试试这个,

[Test]
public void Can_get_simple_streaming_service_to_respond2()
{
    var config = new HttpConfiguration();
    config.Routes.MapHttpAttributeRoutes();
    var server = new HttpServer(config);

    var client = new HttpClient(server);

    var request = new HttpRequestMessage(HttpMethod.Get, "http://in-memory/stream/notepad");

    HttpResponseMessage response = client.SendAsync(request, CancellationToken.None).Result;

    Assert.IsNotNull(response.Content);
    // FAILS, content length is 0
    Assert.Greater(response.Content.Headers.ContentLength, 0);
}

编辑:在评论中,达雷尔给了我真正的答案,我将其移至答案主体以提高知名度:

完成后检查图像流的位置Save。在传递给StreamContent. 此外,您可能需要考虑这样做GetManifestResourceStream,它将保存将字节复制到托管内存中。

于 2013-08-30T01:10:29.087 回答