Reputation: 79
I have the following piece of code within the POST method of my REST API:
using (FileStream outputFile = new FileStream(Path.Combine(fileLocation, fileName), FileMode.OpenOrCreate))
The problem now is that I want to mock the FileStream object but I have no clue how because I cannot inject the object through my constructor. When I do that I get the following error: System.InvalidOperationException: Unable to resolve service for type 'System.IO.FileStream' while attempting to activate 'webservice.Controllers.DataController'.
I also cannot add a layer of abstraction for the constructor of the FileStream object.
Does any of you have some experience with this and if yes, could you help me? Because the 2 ways above are all I can find on google sadly and I rather not write files to my file system while unit testing for obvious reasons.
Upvotes: 0
Views: 334
Reputation: 4140
If you don't want to create files with FileStream, then you have to remove this class from your Controller. One approach would be creating some thing like IFileSystemHelper
with for example SaveFileData
method like this:
namespace MyNamespace
{
using System.IO;
public interface IFileSystemHelper
{
void SaveFileData(string fileLocation, string fileName);
}
public class FileSystemHelper : IFileSystemHelper
{
public void SaveFileData(string fileLocation, string fileName)
{
using (FileStream outputFile = new FileStream(Path.Combine(fileLocation, fileName), FileMode.OpenOrCreate))
{
// TODO: Save file
}
}
}
}
Than you can easily inject this helper to your controller, and then mock it and test.
Upvotes: 1