如何在我上传文件的 Asp.Net core Web api 端点上进行集成测试?

S. *_*nke 3 c# testing integration-testing asp.net-core

我正在编写一个集成测试,用于测试将文件上传到我的端点之一并检查请求结果是否正确!

IFormFile在控制器中使用来接收请求,但收到 400 Bad 请求,因为显然我的文件为空。

如何允许集成测试将文件发送到我的端点?我找到了这篇文章,但只讨论了模拟IFormFile,而不是集成测试。


我的控制器:

[HttpPost]
public async Task<IActionResult> AddFile(IFormFile file)
{
   if (file== null)
   {
       return StatusCode(400, "A file must be supplied");
   }

   // ... code that does stuff with the file..

   return CreatedAtAction("downloadFile", new { id = MADE_UP_ID }, { MADE_UP_ID };
}
Run Code Online (Sandbox Code Playgroud)

我的集成测试:

public class IntegrationTest:
    IClassFixture<CustomWebApplicationFactory<Startup>>
{
    private readonly CustomWebApplicationFactory<Startup> _factory;

    public IntegrationTest(CustomWebApplicationFactory<Startup> factory)
    {
        _factory = factory;
    }

    [Fact]
    public async Task UploadFileTest()
    {
        // Arrange
        var expectedContent = "1";
        var expectedContentType = "application/json; charset=utf-8";

        var url = "api/bijlages";
        var client = _factory.CreateClient();

        // Act
        var file = System.IO.File.OpenRead(@"C:\file.pdf");
        HttpContent fileStreamContent = new StreamContent(file);

        var formData = new MultipartFormDataContent
        {
            { fileStreamContent, "file.pdf", "file.pdf" }
        };

        var response = await client.PostAsync(url, formData);

        fileStreamContent.Dispose();
        formData.Dispose();

        response.EnsureSuccessStatusCode();

        var responseString = await response.Content.ReadAsStringAsync();

        // Assert
        Assert.NotEmpty(responseString);
        Assert.Equal(expectedContent, responseString);
        Assert.Equal(expectedContentType, response.Content.Headers.ContentType.ToString());
    }
Run Code Online (Sandbox Code Playgroud)

我希望你们能帮助我(也可能是其他人!)!

小智 5

你的代码看起来是正确的,除了 keyMultipartFormDataContent应该是file& notfile.pdf

将表单数据更改为{ fileStreamContent, "file", "file.pdf" }