如何在我上传文件的 Asp.Net 核心网络 api 端点上进行集成测试?

How to do an integration test on my Asp.Net core web api endpoint where I upload a file?

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

我在我的控制器中使用 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 };
}

我的集成测试:

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());
    }

我希望你们能在这里帮助我(可能还有其他人!)!

除了 MultipartFormDataContent 中的键应该是 file 而不是 file.pdf

之外,您的代码看起来是正确的

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