jeudi 1 octobre 2015

RenderTargetBitmap in Windows Phone UnitTestApp

I'm trying to write a unit test that will test a visual appearance of my custom control. Therefore I want to capture the control visual appearance using RenderTargetBitmap and then use assertions on result pixels. Here is my test:

[TestClass]
public class UnitTest2
{
    [TestMethod]
    public void TestMethod2()
    {
        //pixels to test
        byte[] pixels = null;

        // Since I create a UI elements, I need to use Dispatcher here.
        // It's impossible to 'await' within unit test method, otherwise you
        // need to add 'async' keyword to the signature of the test method. If I do so,
        // the test runner doesn't recognize this method as a test.
        var task = CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () =>
        {
            // Here I create a visual element that I want to test
            var brush = new SolidColorBrush(Color.FromArgb(255, 255, 0, 0));
            var element = new Border()
            {
                MinWidth = 20,
                MinHeight = 20,
                Background = brush,
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment = VerticalAlignment.Top,
                BorderThickness = new Thickness(0)
            };

            // create an instance of RenderTargetBitmap to render a bitmap 
            var rtb = new RenderTargetBitmap();
            var rtbTask = rtb.RenderAsync(element).AsTask();

            // the following operation lasts for ages
            // May be the reason is that the element is not a part of the VisualTree
            rtbTask.Wait(); 

            var rtbGetPixelsTask = rtb.GetPixelsAsync().AsTask<IBuffer>();
            rtbGetPixelsTask.Wait();
            pixels = rtbGetPixelsTask.Result.ToArray();
        });
        task.AsTask().Wait();

        Assert.AreEqual<byte>(255, pixels[0]);
        Assert.AreEqual<byte>(255, pixels[1]);
        Assert.AreEqual<byte>(255, pixels[2]);
        Assert.AreEqual<byte>(255, pixels[3]);
    }
}

When I debug this test the RendreAsync() operation lasts forever. I suppose that it could be caused by the fact that the element is not a part of the VisualTree, but I cannot find any way to get existing visual tree or to create a new one.

Aucun commentaire:

Enregistrer un commentaire