views:

23

answers:

0

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.