I have a class as follows:
Код: Выделить всё
public class FileUploadRequest
{
public IFormFile FileUploaded { get; set; }
}
Код: Выделить всё
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);
}
}
Код: Выделить всё
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;
}
}
Код: Выделить всё
[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);
}
Источник: https://stackoverflow.com/questions/781 ... sing-xunit
Мобильная версия