我真的可以帮助理解为什么这个单元测试失败了。我怀疑这是由于我处理流的方式。我有许多其他成功使用这种自托管服务器设置的测试,但它们都读取了返回字符串等原语的服务。
以下是有问题的测试:
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);
}
}
答案 0 :(得分: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
之前,您需要将其重置为0。此外,您可能需要考虑执行GetManifestResourceStream
,它会将字节复制到托管内存中。