MKasprzyk MKasprzyk - 4 months ago 113
ASP.NET (C#) Question

How to save string into file in FormFile format

I have got controller whitch support uploadnig files. Inside it is a method whitch validate data in file.

IEnumerable<ValidationResult> Validate(ICollection<IFormFile> files)


It works perfectly. Now I need to write test to this controller. And my question is: how to deliver file form disc into my function in
FormFile
format?

Answer

Generally, the reason to implement something like this as an interface, is to help you be able to test it.

You can easily write a test class which implements IFormFile to pass to your controller method from a test

public class TestFormFile : IFormFile
{
   // Implementation here
}

See the documentation for all the properties & methods you must implement.

Your implementation should probably take your string content in the constructor, and use it when implementing the 3 methods on IFormFile - for example the one for OpenReadStream can be implemnted with use of MemoryStream (Note, you'll need to know the encoding of your test string!):

public class TestFormFile : IFormFile
{
    private string testFileContents;

    public TestFormFile(string testFileContent)
    {
        this.testFileContents = testFileContents;
    }

    public Stream OpenReadStream()
    {
       return new MemoryStream(Encoding.UTF8.GetBytes(testFileContents));
    }

    // Implement Other methods and properties.
}