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

时间:2018-11-23 17:36:40

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

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

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

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

1 个答案:

答案 0 :(得分:3)

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

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