Тестирование API загруженного файла с использованием xunitC#

Место общения программистов C#
Ответить
Гость
 Тестирование API загруженного файла с использованием xunit

Сообщение Гость »


I have a class as follows:

Код: Выделить всё

public class FileUploadRequest {     public IFormFile FileUploaded { get; set; } } 
This is my Controller:

Код: Выделить всё

public class MyController : ControllerBase {     private readonly IMyService _service;     public MyController(IMyService service)     {         _service = service;     }     ///      /// Send a csv file to create a new report.     ///      [HttpPost]     public async Task CreateReport([FromForm] FileUploadRequest inputCsvFile)     {         IdResponse response = await _service.CreateReport(inputCsvFile);         return Created("", response);     } } 
This is my Service:

Код: Выделить всё

public class MyService : IMyService {     private readonly IMyRepository _repository;     private readonly IMapper _mapper;     public MyService(         IMyRepository repository,         IMapper mapper)     {         _repository = repository;         _mapper = mapper;     }     public async Task CreateReport(FileUploadRequest inputCsvFile)     {         if (inputCsvFile.FileUploaded == null)         {             throw new BusinessException(BusinessErrorCode.NO_FILE_UPLOADED);         }         if (inputCsvFile.FileUploaded.ContentType != "text/csv")         {             throw new BusinessException(BusinessErrorCode.INVALID_FILE_TYPE, inputCsvFile.FileUploaded.ContentType);         }         IEnumerable reportDetails = ParseDetailFromCsv(inputCsvFile.FileUploaded);         if(reportDetails == null || !reportDetails.Any())         {             throw new BusinessException(BusinessErrorCode.NO_VALID_DATA);         }         IEnumerable details = _mapper.Map(details);         string result = await _repository.CreateReport(inputCsvFile.FileUploaded, reportDetails);         IdResponse response = new()         {             Id = result         };         return response;     } } 
Currently, I want to test with a sample file saved in the Asset folder of the Test project using xunit. This is my test:

Код: Выделить всё

[Theory] [InlineData("REPORT_DETAILS_TEST.csv")] public async Task CreateReport_CreateSuccessfully(string fileName) {     // Arrange     // Create a context with useInMemory option     using var context = new DataContext(TestHelper.CreateMockDbOptions());     var repository = new MyRepository(context);     var service = new MyService(repository, _mapper);     var controller = new MyController(service);     string exePath = Path.GetDirectoryName(Assembly.GetEntryAssembly()!.Location)!;     string filePath = exePath + $"/Assets/{fileName}";     var formFile = new FormFile(         new MemoryStream(),         0,         new FileInfo(filePath).Length,         "ReportTestFile",         Path.GetFileName(filePath)     );     var inputFile = new FileUploadRequest { FileUploaded = formFile };     // Act     var result = await controller.CreateReport(inputFile);     // Assert     Assert.NotNull(result); } 
However, I realized I couldn't create a FileUploadRequest object the same as when sending using the real API. (ContentType, ContentDisposition, Header fields are null) This causes validation at the service to fail. Is there a way to solve this problem?


Источник: https://stackoverflow.com/questions/781 ... sing-xunit
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»