使用I / O依赖性进行单元测试

时间:2018-04-19 14:07:29

标签: c# wpf nunit rhino-mocks

我想测试下面的类,但是I / O和密封的类依赖性使它变得非常困难。

public class ImageDrawingCombiner
{
    /// <summary>
    ///     Save image to a specified location in path
    /// </summary>
    /// <param name="path">Location to save the image</param>
    /// <param name="surface">The image as canvas</param>
    public void CombineDrawingsIntoImage(Uri path, Canvas surface)
    {
        Size size = new Size(surface.ActualWidth, surface.ActualHeight);

        // Create a render bitmap and push the surface to it
        RenderTargetBitmap renderBitmap = new RenderTargetBitmap(
            (int)size.Width, (int)size.Height, 96d, 96d, PixelFormats.Pbgra32);
        renderBitmap.Render(surface);

        SaveBitmapAsPngImage(path, renderBitmap);
    }

    // SaveBitmapAsPngImage(path, renderBitmap);
    private void SaveBitmapAsPngImage(Uri path, RenderTargetBitmap renderBitmap)
    {
        // Create a file stream for saving image
        using (FileStream outStream = new FileStream(path.LocalPath, FileMode.OpenOrCreate))
        {
            // Use png encoder for our data
            PngBitmapEncoder encoder = new PngBitmapEncoder();
            // push the rendered bitmap to it
            encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
            // save the data to the stream
            encoder.Save(outStream);
        }
    }
}

稍微重构了SaveBitmapAsPngImage方法:

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

}

公开让它可测试(代码味道?)。它仍在使用FileStream。有人会建议用MemoryStream和/或Factory模式替换它,但最后它必须保存到图像文件的某个地方。

即使我用包装器或接口(SystemInterface)替换所有基于I / O的调用:   - 实例应该在哪里初始化?在复合根?泡泡了很多......   - 如何避免使用DI的“最多3个构造函数参数”规则?   - 对于这个简单的功能来说,这听起来很多

测试应确保生成图像文件。

编辑: 试图运行@Nkosi Moq测试,但它需要修复。取代:

var renderBitmap = new Canvas();

使用:

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

测试结果:

  

BitmapServiceTest.BitmapService_Should_SaveBitmapAsPngImage投掷   exception:System.IO.IOException:无法从流中读取。 ---&GT;   System.Runtime.InteropServices.COMException:来自HRESULT的异常:   0x88982F72       在System.Windows.Media.Imaging.BitmapEncoder.Save(Stream stream)

似乎编码器对模拟的Moq流不满意。 PngBitmapEncoder依赖性是否也应该通过注入方法(并在测试中模拟)?

1 个答案:

答案 0 :(得分:1)

这完全是设计问题。尽量避免与实现问题紧密耦合(类应该依赖于抽象而不是结果)。

根据您当前的设计考虑以下内容

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

public interface IFileSystem {
    Stream OpenOrCreateFileStream(string path);
}

public class PhysicalFileSystem : IFileSystem {
    public Stream OpenOrCreateFileStream(string path) {
        return new FileStream(path, FileMode.OpenOrCreate);
    }
}

public class BitmapService : IBitmapService {
    private readonly IFileSystem fileSystem;

    public BitmapService(IFileSystem fileSystem) {
        this.fileSystem = fileSystem;
    }

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

public interface IImageDrawingCombiner {
    void CombineDrawingsIntoImage(Uri path, Canvas surface);
}

public class ImageDrawingCombiner : IImageDrawingCombiner {
    private readonly IBitmapService service;

    public ImageDrawingCombiner(IBitmapService service) {
        this.service = service;
    }

    /// <summary>
    ///  Save image to a specified location in path
    /// </summary>
    /// <param name="path">Location to save the image</param>
    /// <param name="surface">The image as canvas</param>
    public void CombineDrawingsIntoImage(Uri path, Canvas surface) {
        var size = new Size(surface.ActualWidth, surface.ActualHeight);
        // Create a render bitmap and push the surface to it
        var renderBitmap = new RenderTargetBitmap(
            (int)size.Width, (int)size.Height, 96d, 96d, PixelFormats.Pbgra32);
        renderBitmap.Render(surface);
        service.SaveBitmapAsPngImage(path, renderBitmap);
    }
}

FileStream是一个实现问题,可以在单独进行单元测试时抽象出来。

上面的每个实现都可以单独测试,并且可以根据需要进行模拟和注入。在生产中,可以使用DI容器在组合根中添加依赖项。

  

如何断言encoder.Save(outStream)被调用?

鉴于您控制了流的创建并且System.IO.Stream是抽象的,您可以轻松地模拟它并验证它是否已写入,因为encode.Save在执行其时必须写入流功能

这是一个使用Moq模拟框架的简单示例,该框架针对上一个示例中的重构代码。

[TestClass]
public class BitmapServiceTest {
    [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);
        var renderBitmap = new Canvas();
        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>()));
    }
}

评论员建议使用内存流,我建议在大多数其他方案中使用,但在这种情况下,流被包含在using语句中的被测试方法中。这将使得调用成员在被处理后抛出异常。通过直接模拟流,您可以更好地控制断言所谓的内容。