Stubbing a File Stream, Memory Stream, or Stream

Here’s the class that has a Func setup as a property. The reason this is setup, is so that the stream can actually be stubbed on the ComplianceReportingJob. Otherwise if the Stream was just being used as is, instantiated in the class, or passed in via injection, we still couldn’t get it mocked or stubbed. Especially if the class ComplianceReportingJob is under test.

public class ComplianceReportingJob : IJob
{
    readonly ITradeRepository tradeRepo;
    readonly IFileSystem fileSys;
    
    public ComplianceReportingJob(ITradeRepository tradeRepository, IFileSystem fileSystem)
    {
        tradeRepo = tradeRepository;
        StreamedFile = filename => new FileStream(filename, FileMode.Create);
    }

    public Func<string, Stream> StreamedFile { get; set; }
}

What we have here is the context being setup, with the property being stubbed with a fake StreamedFile = filename => new MemoryStream(). So if you’re looking for a way to test streams with .NET, this is a way around the limitations of the framework.

public class with_a_compliance_report_job
{
    protected static ITradeRepository tradeRepository;
    protected static IFileSystem fileSys;
    protected static ComplianceReportingJob job;

    Establish context = () =>
    {
        tradeRepository = Substitute.For<ITradeRepository>();
        fileSys = Substitute.For<IFileSystem>();
       
        reportContent = FizzWare.NBuilder.Builder<TradeComplianceViewModel>.CreateListOfSize(10).Build().ToList();

        tradeRepository.GetComplianceReport().Returns(reportContent);
        fileSys.DirectoryExists(string.Empty).ReturnsForAnyArgs(true);

        job = new ComplianceReportingJob(tradeRepository, fileSys)
                    {StreamedFile = filename => new MemoryStream()};
    };

    protected static List<TradeComplianceViewModel> reportContent;
}

This is a pretty sweet solution, for now. The ideal solution however, would be that Microsoft fixes the framework, which is very unlikely to happen. The whole closed, sealed, and otherwise locked up framework stack is a massive problem with testability. Which then directly impacts maintainability and other things over time.

Shout it

2 thoughts on “Stubbing a File Stream, Memory Stream, or Stream

  1. DotNetShoutout

  2. Stubbing a File Stream, Memory Stream, or... | .NET, Agile and Testing | Syngu

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s