0

I have an api that receives an xlsx file and read it, it works fine wiht the real file, but when i mock to test it does not.

I have this api test that creates an IFomFile

public IFormFile CreateCorrectClientByFileMock() {

            var fileName = "fileName.xlsx";
            var stream = new MemoryStream();
            var writer = new StreamWriter(stream);
            writer.WriteLine("name;email;date");
            writer.Flush();
            stream.Position = 0;
            IFormFile file = new FormFile(stream, 0, stream.Length, "id_from_form", fileName)
            {
                Headers = new HeaderDictionary(),
                ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            };
            stream.Close();
            return file;
        }`

and send it to this function:

public List<Client> ReadFile(IFormFile file){
                using var stream = file.OpenReadStream();
                XLWorkbook wb = new(stream);

and does all the processes to read...... 

}

it trowns an "System.IO.FileFormatException:'File contains corrupted data.'" at line "XLWorkbook wb = new(stream);"

When i call the function with a real file it works fine, but when I try To create the IFormFile for test it does not.

Aluan Haddad
  • 29,886
  • 8
  • 72
  • 84
  • Returning disposed streams (as code shown in the post) is usually bad idea... You may want to add comments and remove calls that close the stream. (Not an answer as normally error in this case should be "accessing disposed object" and not the one in the post). – Alexei Levenkov Mar 01 '23 at 21:02
  • It doesn't appear you are creating a valid Open XML document in your `CreateCorrectClientByFileMock` method. `writer.WriteLine("name;email;date");` this doesn't represent a valid Open XML document. [open-xml/structure-of-a-spreadsheetml-document](https://learn.microsoft.com/en-us/office/open-xml/structure-of-a-spreadsheetml-document) – quaabaam Mar 01 '23 at 21:30
  • Does this answer your question? [How to create Excel file using OpenXML without creating a local file?](https://stackoverflow.com/questions/29887503/how-to-create-excel-file-using-openxml-without-creating-a-local-file) – quaabaam Mar 01 '23 at 21:34

0 Answers0