这是Unit testing with I/O dependencies的后续问题。
如何让PngBitmapEncoder接受包装/模拟的FileStream?
在BitmapService.SaveBitmapAsPngImage()中我想断言位图编码器调用流保存: bitmapEncoder.Save(outStream.StreamInstance);
Rhino模拟测试需要PngBitmapEncoder的“有效”FileStream:
[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测试结果:
System.ArgumentNullException:值不能为null。 参数名称:stream
at System.Windows.Media.StreamAsIStream.IStreamFrom(Stream stream)
在System.Windows.Media.Imaging.BitmapEncoder.Save(Stream stream)
at BitmapService.SaveBitmapAsPngImage(Uri path,BitmapSource renderBitmap)
我更喜欢犀牛嘲笑,但这里是@Nkosi的Moq测试。不幸的是,它也没有工作:
[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测试结果:
BitmapServiceTest.BitmapService_Should_SaveBitmapAsPngImage投掷 exception:System.IO.IOException:无法从流中读取。 ---&GT; System.Runtime.InteropServices.COMException:来自HRESULT的异常: 0x88982F72 在System.Windows.Media.Imaging.BitmapEncoder.Save(Stream stream)
因此测试试图实际使用该流。
待测班级:
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);
}
}
}
答案 0 :(得分:1)
正如我在评论中所建议的那样,如果使用模拟框架模拟Stream
不适合您,请考虑通过包装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);
}
}
这将有你所有的管道。唯一的问题是,当流与Dispose
语句一起使用时,您必须覆盖using
方法。
然后会更新测试以使用“假”流
[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
}
在我看来,确实没有必要嘲笑或抽象PngBitmapEncoder
,因为这是一个实施问题。
答案 1 :(得分:0)
非常感谢@NKosi引领正确方向前进。 为了完整性,我想发布NUnit,Rhino模拟测试。
[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
}
从服务中删除了BitmapEncoder抽象:
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);
}
}
}
我对整洁干净的解决方案非常满意。谢谢@NKosi和StackOverflow;)