Faking Stream for sealed PngBitmapEncoder

0

This is a follow up question to Unit testing with I/O dependencies.

How do I make PngBitmapEncoder to accept wrapped/mocked FileStream?

In BitmapService.SaveBitmapAsPngImage() I want to assert that bitmap encoder calls stream save: bitmapEncoder.Save(outStream.StreamInstance);

Rhino mock test which needs "a valid" FileStream for the PngBitmapEncoder:

[Test]
public void BitmapService_Should_SaveBitmapAsPngImage_RhinoMocks()
{
    // Arrange
    IFile fileMock = MockRepository.GenerateStrictMock<IFile>();
    IFileStream fileStreamWrapperMock = MockRepository.GenerateStub<IFileStream>();
    fileMock.Expect(x => x.Open(string.Empty, FileMode.OpenOrCreate))
        .IgnoreArguments().Return(fileStreamWrapperMock);
    var bitmapEncoderFactory = MockRepository.GenerateStub<IBitmapEncoderFactory>();

    PngBitmapEncoder pngBitmapEncoder = new PngBitmapEncoder();
    bitmapEncoderFactory.Expect(x => x.CreateBitmapEncoder()).Return(pngBitmapEncoder);

    BitmapService sut = new BitmapService(fileMock, new PngBitmapEncoderFactory());
    Size renderSize = new Size(100, 50);
    RenderTargetBitmap renderBitmap = new RenderTargetBitmap(
        (int)renderSize.Width, (int)renderSize.Height, 96d, 96d, PixelFormats.Pbgra32);

    // Act
    sut.SaveBitmapAsPngImage(new Uri("//A_valid_path"), renderBitmap);

    // Assert
    pngBitmapEncoder.AssertWasCalled(x => x.Save(fileStreamWrapperMock.FileStreamInstance));
}

Rhino test result:

System.ArgumentNullException : Value cannot be null. Parameter name: stream

at System.Windows.Media.StreamAsIStream.IStreamFrom(Stream stream)

at System.Windows.Media.Imaging.BitmapEncoder.Save(Stream stream)

at BitmapService.SaveBitmapAsPngImage(Uri path, BitmapSource renderBitmap)

I prefer the Rhino mocks but here is the Moq test by @Nkosi. Unfortunately, it is not working either:

[TestMethod]
public void BitmapService_Should_SaveBitmapAsPngImage()
{
    //Arrange
    var mockedStream = Mock.Of<Stream>(_ => _.CanRead == true && _.CanWrite == true);
    Mock.Get(mockedStream).SetupAllProperties();
    var fileSystemMock = new Mock<IFileSystem>();
    fileSystemMock
        .Setup(_ => _.OpenOrCreateFileStream(It.IsAny<string>()))
        .Returns(mockedStream);

    var sut = new BitmapService(fileSystemMock.Object);
    Size renderSize = new Size(100, 50);
    var renderBitmap = new RenderTargetBitmap(
        (int)renderSize.Width, (int)renderSize.Height, 96d, 96d, PixelFormats.Pbgra32);
    var path = new Uri("//A_valid_path");

    //Act
    sut.SaveBitmapAsPngImage(path, renderBitmap);

    //Assert
    Mock.Get(mockedStream)
        .Verify(_ => _.Write(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>()));
}

Moq test result:

BitmapServiceTest.BitmapService_Should_SaveBitmapAsPngImage threw exception: System.IO.IOException: Cannot read from the stream. ---> System.Runtime.InteropServices.COMException: Exception from HRESULT: 0x88982F72 at System.Windows.Media.Imaging.BitmapEncoder.Save(Stream stream)

So the test tries to actually use that Stream.


Class under test:

using System;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using SystemInterface.IO;
using SystemWrapper.IO;

public interface IBitmapService
{
    void SaveBitmapAsPngImage(Uri path, BitmapSource renderBitmap);
}

public interface IBitmapEncoderFactory
{
    BitmapEncoder CreateBitmapEncoder();
}

public class PngBitmapEncoderFactory : IBitmapEncoderFactory
{
    public BitmapEncoder CreateBitmapEncoder()
    {
        return new PngBitmapEncoder();
    }
}

public class BitmapService : IBitmapService
{
    private readonly IFile _fileWrapper;
    private readonly IBitmapEncoderFactory _bitmapEncoderFactory;

    public BitmapService(IFile fileWrapper, IBitmapEncoderFactory bitmapEncoderFactory)
    {
        _fileWrapper = fileWrapper;
        _bitmapEncoderFactory = bitmapEncoderFactory;
    }

    public void SaveBitmapAsPngImage(Uri path, BitmapSource renderBitmap)
    {
        // Create a file stream for saving image
        using (IStream outStream = _fileWrapper
            .Open(path.LocalPath, FileMode.OpenOrCreate))
        {
            // Use bitmap encoder for our data
            BitmapEncoder bitmapEncoder = _bitmapEncoderFactory.CreateBitmapEncoder();
            // push the rendered bitmap to it
            bitmapEncoder.Frames.Add(BitmapFrame.Create(renderBitmap));

            // The problem: Expects real Stream as parameter!!!
            bitmapEncoder.Save(outStream.StreamInstance);
        }
    }
}
c#
unit-testing
moq
rhino-mocks
asked on Stack Overflow Apr 26, 2018 by J Pollack • edited Apr 28, 2018 by J Pollack

2 Answers

1

As I had suggested in the comments, If mocking the Stream was not working for you with a mocking framework, consider creating a mock/stub by wrapping a MemoryStream,

public class MockedFileStream : MemoryStream {
    protected override void Dispose(bool disposing) {
        //base.Dispose(disposing);
        //No Op fr the purposes of the test.
    }

    public override void Close() {
        //base.Close();
        //No Op fr the purposes of the test.
    }

    public void CustomDispose() {
        base.Dispose(true);
        GC.SuppressFinalize(this);
    }
}

which would have all the plumbing already there for you. The only catch being that you would have to override the Dispose method as the stream is being used with a using statement.

The test would then be updated to use the "fake" stream

[TestMethod]
public void BitmapService_Should_SaveBitmapAsPngImage() {
    //Arrange
    var mockedStream = new MockedFileStream();
    var fileSystemMock = new Mock<ImageDrawingCombiner3.IFileSystem>();
    fileSystemMock
        .Setup(_ => _.OpenOrCreateFileStream(It.IsAny<string>()))
        .Returns(mockedStream);

    var sut = new ImageDrawingCombiner3.BitmapService(fileSystemMock.Object);
    Size renderSize = new Size(100, 50);
    var renderBitmap = new RenderTargetBitmap(
        (int)renderSize.Width, (int)renderSize.Height, 96d, 96d, PixelFormats.Pbgra32);
    var path = new Uri("//A_valid_path");

    //Act
    sut.SaveBitmapAsPngImage(path, renderBitmap);

    //Assert
    mockedStream.Length.Should().BeGreaterThan(0); //data was written to it.

    mockedStream.CustomDispose(); //done with stream
}

There should really be no need to mock or abstract PngBitmapEncoder in my opinion as it is an implementation concern.

answered on Stack Overflow Apr 26, 2018 by Nkosi • edited Apr 26, 2018 by Nkosi
0

Big thanks to @NKosi for leading the way to the right direction. For completeness I want to post the NUnit, Rhino mock test.

[Test]
public void ShouldSaveBitmapAsPngImage()
{
    // Arrange
    Uri pathToFile = new Uri("//A_valid_path");
    IFileSystem fileSystemMock = MockRepository.GenerateStrictMock<IFileSystem>();
    MockedFileStream mockedFileStream = new MockedFileStream();
    fileSystemMock.Expect(x => x.OpenOrCreateFileStream(pathToFile.AbsolutePath))
        .IgnoreArguments().Return(mockedFileStream);

    BitmapService sut = new BitmapService(fileSystemMock);
    Size renderSize = new Size(100, 50);
    RenderTargetBitmap renderBitmap = new RenderTargetBitmap(
        (int)renderSize.Width, (int)renderSize.Height, 96d, 96d, PixelFormats.Pbgra32);

    // Act
    sut.SaveBitmapAsPngImage(pathToFile, renderBitmap);

    // Assert
    // Was data was written to it?
    Assert.That(mockedFileStream.Length, Is.GreaterThan(0));

    mockedFileStream.CustomDispose(); //done with stream
}

And got rid of the BitmapEncoder abstraction from the service:

public class BitmapService : IBitmapService
{
    private readonly IFileSystem _fileSystem;

    public BitmapService(IFileSystem fileSystem)
    {
        _fileSystem = fileSystem;
    }

    public void SaveBitmapAsPngImage(Uri path, BitmapSource renderBitmap)
    {
        // Create a file stream for saving image
        using (Stream outStream = _fileSystem.OpenOrCreateFileStream(path.LocalPath))
        {
            // Use bitmap encoder for our data
            BitmapEncoder bitmapEncoder = new PngBitmapEncoder();
            // push the rendered bitmap to it
            bitmapEncoder.Frames.Add(BitmapFrame.Create(renderBitmap));
            // save the data to the stream
            bitmapEncoder.Save(outStream);
        }
    }
}

I am really happy with the neat and clean solution. Thanks @NKosi and StackOverflow ;)

answered on Stack Overflow Apr 28, 2018 by J Pollack

User contributions licensed under CC BY-SA 3.0