gpt4 book ai didi

unit-testing - 单元测试自定义 Web API MediaTypeFormatter

转载 作者:行者123 更新时间:2023-12-03 14:36:29 25 4
gpt4 key购买 nike

我有 extended the JsonMediaTypeFormatter 为了在 JSON 中为 decorated with a custom attribute 的类型生成“根”对象.

我将如何对这个格式化程序进行单元测试?我对如何查看WriteToStreamAsync(..)特别感兴趣。方法。

最佳答案

免费的 O'Reilly 电子书 Designing Evolvable Web APIs with ASP.NEThow to test a MediaTypeFormatter 上有一些非常有用的具体建议.

这是他们对 WriteToStreamAsync 的测试方法. (这是我对 test WebApiContrib.Formatters.Xlsx 采取的方法,而且效果很好。)

var ms = new MemoryStream();

var content = new FakeContent();
content.Headers.ContentType = new MediaTypeHeaderValue("application/atom+xml");

var formatter = new SyndicationMediaTypeFormatter();

var task = formatter.WriteToStreamAsync(typeof(List<ItemToSerialize>),
new List<ItemToSerialize> { new ItemToSerialize { ItemName = "Test" }},
ms,
content,
new FakeTransport()
);

task.Wait();

ms.Seek(0, SeekOrigin.Begin);

var atomFormatter = new Atom10FeedFormatter();
atomFormatter.ReadFrom(XmlReader.Create(ms));

Assert.Equal(1, atomFormatter.Feed.Items.Count());

注意事项:
  • FakeContentFakeTransport都是假货HttpContentTransportContext类,您可以在文章中找到相关代码。
  • Task.Wait用于阻塞执行直到WriteToStreamAsync返回的任务完成。
  • 格式化程序的输出写入 MemoryStream ,然后可以由合适的格式化程序/反序列化程序读取和解析,以便您可以进行测试断言。


  • 或者,您可以编写一个示例 Controller 实现,启动它运行并使用客户端调用 Controller 方法进行测试。这就是 Chris Missal 在 WebApiContrib.Formatting.Bson 中所做的.

    Controller 不需要很复杂:

    public class TestController : ApiController
    {
    public Item Get(int id)
    {
    return new Item { ID = id };
    }
    // ...
    }

    设置服务器和客户端:

    [TestFixtureSetUp]
    public void fixture_init()
    {
    var config = new HttpConfiguration();
    config.Formatters.Add(new TestMediaTypeFormatter());
    config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "{controller}/{id}",
    defaults: new {id = RouteParameter.Optional}
    );

    var server = new HttpServer(config);

    _client = new HttpClient(server);
    _client.BaseAddress = new Uri("http://www.test.com/");
    _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/bson"));
    }

    现在,在您的测试中,调用客户端上的方法并对结果执行您想要的操作:

    var response = _client.GetAsync("test/1").Result;
    var result = response.Content.ReadAsAsync<Item>(new HashSet<MediaTypeFormatter> {new TestMediaTypeFormatter()}).Result;

    关于unit-testing - 单元测试自定义 Web API MediaTypeFormatter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18268632/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com