【问题标题】:How to do an integration test on my Asp.Net core web api endpoint where I upload a file?如何在我上传文件的 Asp.Net 核心 Web api 端点上进行集成测试?
【发布时间】:2018-11-23 17:36:39
【问题描述】:

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

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

如何允许集成测试将文件发送到我的端点?我找到了this post,但它只涉及模拟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());
    }

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

【问题讨论】:

  • 你能使用像 Fiddler 这样的工具来检查实际发布的内容吗?

标签: c# testing asp.net-core integration-testing


【解决方案1】:

您的代码看起来是正确的,除了 MultipartFormDataContent 中的键应该是 file 而不是 file.pdf

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-20
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 2019-10-10
    • 1970-01-01
    • 1970-01-01
    • 2011-09-04
    相关资源
    最近更新 更多