I have a custom control MyControl which inherits from Canvas and which has its own logic inside the OnRender-Method.
It should draw some rectangles and text into the drawing context.
public class MyControl : Canvas
{
protected override void OnRender(DrawingContext dc)
{
// do something like dc.DrawRectangle(...);
// do something like dc.DrawText(...);
}
}
Since I have to develop test-driven, I want to unit test the OnRender-Method.
I tried several solutions which did not work. All of them required an inherited class for testing purpose, which I will call TestingMyControl and which exposes the OnRender-Method in the follwing form:
public class TestingMyControl : MyControl
{
public void Render(DrawingContext dc)
{
base.OnRender(dc);
}
}
Since DrawingContext is an abstract class, I thought I could implement a test class which implements DrawingContext. I could then collect all the rectangles and text which it should draw, and make assertions against this. Problem: DrawingContext has an internal constructor, so I cannot inherit from it.
Since DrawingContext is an abstract class, I thought I could create a Mock of it.
Problem: it has some internal abstract Methods, so Rhino-Mocks could not create a proxy, since it cannot implement these internal abstract Methods.
So I have the problem, that I cannot test the OnRender-Method, since I cannot create an Instance of DrawingContext...
The solution is, to create the DrawingContext out of an DrawingGroup.
public class TestingMyControl : MyControl
{
public DrawingGroup Render()
{
var drawingGroup = new DrawingGroup();
using (var drawingContext = drawingGroup.Open())
{
base.OnRender(drawingContext);
}
return drawingGroup;
}
}
So the fixture will look like:
[Test]
public void Should_render()
{
var controlToTest = new TestingMyControl();
var drawingGroup = controlToTest.Render();
var drawing = drawingGroup.Children[0] as GeometryDrawing;
Assert.That(drawing.Brush, Is.EqualTo(Brushes.Black));
Assert.That(drawing.Pen.Brush, Is.EqualTo(Brushes.SeaGreen));
Assert.That(drawing.Pen.Thickness, Is.EqualTo(0.6));
Assert.That(drawing.Bounds.X, Is.EqualTo(5));
Assert.That(drawing.Bounds.Y, Is.EqualTo(15));
Assert.That(drawing.Bounds.Width, Is.EqualTo(25));
Assert.That(drawing.Bounds.Height, Is.EqualTo(35));
}
This requires the follwing production code:
public class MyControl : Canvas
{
protected override void OnRender(DrawingContext dc)
{
dc.DrawRectangle(Brushes.Black, new Pen(Brushes.SeaGreen, 0.6), new Rect(5, 15, 25, 35));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With