如何对将字符串添加到位图的代码进行单元测试
我正在尝试对一些将字符串添加到位图的代码进行单元测试。当应用程序运行时,代码可以正常工作。但我在为其编写单元测试时遇到了麻烦。
这就是 SUT:
public byte[] AddStringToImage(byte[] image, string caption)
{
using(var mstream = new MemoryStream(image))
using (var bmp = new Bitmap(mstream))
{
using (var g = Graphics.FromImage(bmp))
{
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
g.DrawString(caption, new Font("Tahoma", 30), Brushes.Red, 0, 0);
}
var ms = new MemoryStream();
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
return ms.ToArray();
}
}
我希望它就像向其传递字节数组和字符串一样简单。像这样:
var imageContents = new byte[1000];
new Random().NextBytes(imageContents);
const string Caption = "Sold";
AddStringToImage(imageContents, Caption);
但它抛出一个 参数无效 异常:
using (var bmp = new Bitmap(mstream))
我认为字节数组需要采用某种格式,这是有道理的。
我将如何在单元测试中创建合适的字节数组,以便将其传递给 addStringToImage 方法。
I'm trying to unit test some code that adds a string to a bitmap. The code works fine when the app is running. But I'm having trouble writing a unit test for it.
This is the SUT:
public byte[] AddStringToImage(byte[] image, string caption)
{
using(var mstream = new MemoryStream(image))
using (var bmp = new Bitmap(mstream))
{
using (var g = Graphics.FromImage(bmp))
{
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
g.DrawString(caption, new Font("Tahoma", 30), Brushes.Red, 0, 0);
}
var ms = new MemoryStream();
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
return ms.ToArray();
}
}
I hoped it might be as easy as passing a byte array and string to it. Something like so:
var imageContents = new byte[1000];
new Random().NextBytes(imageContents);
const string Caption = "Sold";
AddStringToImage(imageContents, Caption);
but it throws a Parameter is not valid exception on the line:
using (var bmp = new Bitmap(mstream))
I presume the byte array needs to be in a certain format, which makes sense.
How would I go about creating a suitable byte array in a unit test so I can pass it to the addStringToImage method.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要从 BITMAP 标头构建数组并仅随机化图像字节。
BITMAP 格式可在此处获取。
顺便说一句,您正在编写的并不是真正的单元测试,而是集成测试,因为它实际上至少涉及两层:您的代码和实例化 BITMAP 类的框架代码。
如果你想真正对其进行单元测试,你需要使用模拟。
You need to construct your array out of the BITMAP header and randomize the image bytes only.
The BITMAP format is available here.
By the way, what you're writing is not really a unit test, it is an integration test, since it actually involves at least 2 layers: your code and the framework code that instantiates the BITMAP class.
If you want to really unit test this you need to use mocks.