unit testing custom OnRender-Method

前端 未结 1 541
攒了一身酷
攒了一身酷 2021-01-14 20:20

I have a custom control MyControl which inherits from Canvas and which has its own logic inside the OnRender-Method. It should draw so

相关标签:
1条回答
  • 2021-01-14 20:45

    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));
        }
    }
    
    0 讨论(0)
提交回复
热议问题