Skip to main content
 首页 » 编程设计

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

2024年02月25日34zhoujg

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

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

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


我的 Controller :

[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"}