简体   繁体   English

如何在测试中创建文件并将其转换为 HttpContent 对象?

[英]How can I create a file within a test and convert it to a HttpContent object?

I am writing tests to test API responses.我正在编写测试来测试 API 响应。 I need to test the response for a file upload to a .NET API.我需要测试文件上传到 .NET API 的响应。

So I need to pass a mock file through my post method as a HttpContent object.所以我需要通过我的 post 方法将一个模拟文件作为 HttpContent 对象传递。 How can this be achieved?如何做到这一点? is there a way to create a file object within the test and convert it to the HttpContent object?有没有办法在测试中创建文件对象并将其转换为 HttpContent 对象?

If it helps to know, I am using Xunit testing framework.如果它有助于了解,我正在使用 Xunit 测试框架。

I assume HttpContent in the question is for HttpClient .我假设问题中的HttpContent是针对HttpClient

HttpContent is an abstract class, which cannot be instantiated. HttpContent是一个抽象类,不能被实例化。 You will need to create one concrete derived class based on your request's content type.您需要根据请求的内容类型创建一个具体的派生类。

In this case, as per the comment, you can use MultipartFormDataContent :在这种情况下,根据评论,您可以使用MultipartFormDataContent

var content = new MultipartFormDataContent("your boundary");
var file = File.OpenRead("file path");
content.Add(new StreamContent(file), "name", "fileName");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM