'C# Unit Test How to mocK IFormFileCollection?
I have a method that uses IFormFileCollection and i want to unit test it.
my method :
public IActionResultUploadBankAccount(){
IFormFileCollection files = Request.Form.Files;
if (!files.Any()) return Ok(new GeneralDto.Response("Check your files!"));
// and my codes
}
and my authorize codes :
MockAuthorize.cs :
public static void Authorize(this ControllerBase controller,....){
//my codes
var bytes = Encoding.UTF8.GetBytes("This is a text file");
IFormFile file = new FormFile(new MemoryStream(bytes), 0, bytes.Length, "Data", @"\Mock\Images\testFile.jpg");
}
while i'm trying to test it, method throws error that says:
System.NullReferenceException : Object reference not set to an instance of an object.
What am i doing wrong? or is there any way to test FormFileCollection?
Solution 1:[1]
As FormFileCollection is part of .NET, you shouldn't be testing it. Microsoft will have tested this functionality.
All you should be testing is your own logic.
In order to mock IFormFileCollection I would use a mocking framework such as Moq and do something like this
private Mock<IFormFileCollection> _formFileCollectionMock;
private IClassToTest _sut;
public YourConstructor()
{
_formFileCollectionMock= new Mock<IFormFileCollection>();
_sut = new ClassToTest(_formFileCollectionMock.Object);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ben D |
