簡體   English   中英

如何在我上傳文件的Asp.Net核心web api端點上進行集成測試?

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

我正在編寫一個集成測試,測試文件上傳到我的一個端點,並檢查請求結果是否正確!

我在我的控制器中使用IFormFile來接收請求,但是我收到400 Bad請求,因為顯然我的文件為null。

如何允許集成測試將文件發送到我的端點? 我發現這篇文章,但只討論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

將formdata更改為{ fileStreamContent, "file", "file.pdf" }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM