How to unit test code that adds a string to a bit map
I'm trying to unit test some code that adds a string to a bitmap. The code works fine when the开发者_JS百科 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.
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.
精彩评论