如何对使用 VisualTreeHelper 的内容进行单元测试?

发布于 2024-10-04 07:33:07 字数 1168 浏览 5 评论 0原文

我有这个静态辅助函数:

    public static DependencyObject GetParentObject(DependencyObject child)
    {
        if (child == null) return null;
        ContentElement contentElement = child as ContentElement;

        if (contentElement != null)
        {
            var parent = ContentOperations.GetParent(contentElement);
            if (parent != null) return parent;

            var fce = contentElement as FrameworkContentElement;
            return fce != null ? fce.Parent : null;
        }

        //if it's not a ContentElement, rely on VisualTreeHelper
        return VisualTreeHelper.GetParent(child);
    }

它在真实的应用程序中工作,但我正在尝试为其编写一些单元测试。这是我的第一次尝试:

    [Test]
    public void GetParentObject_returns_immediate_parent()
    {
        var contentControl = new ContentControl();
        var textBox = new TextBox();

        contentControl.BeginInit();
        contentControl.Content = textBox;
        contentControl.EndInit();

        var result = UIHelper.GetParentObject(textBox);
        Assert.AreSame(contentControl, result);
    }

不幸的是,它失败了,因为 VisualTreeHelper 返回 null。我如何模拟一个可行的视觉树?

I have this static helper function:

    public static DependencyObject GetParentObject(DependencyObject child)
    {
        if (child == null) return null;
        ContentElement contentElement = child as ContentElement;

        if (contentElement != null)
        {
            var parent = ContentOperations.GetParent(contentElement);
            if (parent != null) return parent;

            var fce = contentElement as FrameworkContentElement;
            return fce != null ? fce.Parent : null;
        }

        //if it's not a ContentElement, rely on VisualTreeHelper
        return VisualTreeHelper.GetParent(child);
    }

It works in a real application, but I'm trying to write some unit tests for it. Here's my first attempt:

    [Test]
    public void GetParentObject_returns_immediate_parent()
    {
        var contentControl = new ContentControl();
        var textBox = new TextBox();

        contentControl.BeginInit();
        contentControl.Content = textBox;
        contentControl.EndInit();

        var result = UIHelper.GetParentObject(textBox);
        Assert.AreSame(contentControl, result);
    }

Unfortunately it fails because VisualTreeHelper is returning null. How can I mock up a visual tree that will work?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

花开半夏魅人心 2024-10-11 07:33:07

基于这里的答案 通过 Wpf-controls 打印文档并转换对于 XPS 我想出了以下扩展方法来创建可视化树。它在 NUnit 中运行良好,无需 STA 线程或其他任何东西。

/// <summary>
/// Render a UIElement such that the visual tree is generated, 
/// without actually displaying the UIElement
/// anywhere
/// </summary>
public static void CreateVisualTree(this UIElement element)
{
    var fixedDoc = new FixedDocument();
    var pageContent = new PageContent();
    var fixedPage = new FixedPage();
    fixedPage.Children.Add(element);
    pageContent.ToMaybeOf<IAddChild>().Do(c => c.AddChild(fixedPage));
    fixedDoc.Pages.Add(pageContent);

    var f = new XpsSerializerFactory();
    var w = f.CreateSerializerWriter(new MemoryStream());
    w.Write(fixedDoc);
}

请注意,

  • 另一个答案使用了 Reach-dll 的 API,它看起来不像我看到的 API。我假设 .NEt Framework 版本 3.5 和 4.0 之间存在差异,
  • ToMaybeOf 内容基本上意味着将 pageContent 视为 IAddChild 并执行操作该接口
  • 不适用于类型为Window的元素,因为该元素本质上是作为子项添加到Visual中的,而Window会对此强烈抱怨。

Based on this answer here on printing documents via Wpf-controls and convert to XPS I came up with the following extension method to create the visual tree. It works well within NUnit without STA-thread or anything.

/// <summary>
/// Render a UIElement such that the visual tree is generated, 
/// without actually displaying the UIElement
/// anywhere
/// </summary>
public static void CreateVisualTree(this UIElement element)
{
    var fixedDoc = new FixedDocument();
    var pageContent = new PageContent();
    var fixedPage = new FixedPage();
    fixedPage.Children.Add(element);
    pageContent.ToMaybeOf<IAddChild>().Do(c => c.AddChild(fixedPage));
    fixedDoc.Pages.Add(pageContent);

    var f = new XpsSerializerFactory();
    var w = f.CreateSerializerWriter(new MemoryStream());
    w.Write(fixedDoc);
}

Please note that

  • the other answer uses an API of the Reach-dll that does not look like the API I am seeing. I assume that there are differences between .NEt Framework versions 3.5 and 4.0
  • the ToMaybeOf stuff basically means to treat pageContent as IAddChild and do an action on that interface
  • this will not work with an element of type Window since the element is essentially added as a child to a Visual and Window will complain bitterly about this.
治碍 2024-10-11 07:33:07

这就是静力学存在问题的原因。

您可以抽象接口背后的功能并创建使用静态方法的默认实现。然后,您可以使用依赖项注入,这使得此单元测试变得微不足道 - 模拟对 IVisualTreeHelper 的依赖项或滚动您自己的存根实现,您可以将其配置为返回您分配的任何值。

public class Foo
{
    static IVisualTreeHelper visualTreeHelper;

    static Foo()
    {
        Foo.visualTreeHelper = new FrameworkVisualTreeHelper();
    }

    public Foo(IVisualTreeHelper visualTreeHelper)
    {
        Foo.visualTreeHelper = visualTreeHelper;
    }

    public static DependencyObject GetParentObject(DependencyObject child)
   {
       if (child == null) return null;
       ContentElement contentElement = child as ContentElement;

       if (contentElement != null)
       {
           var parent = ContentOperations.GetParent(contentElement);
           if (parent != null) return parent;

           var fce = contentElement as FrameworkContentElement;
           return fce != null ? fce.Parent : null;
       }

       //if it's not a ContentElement, rely on the IVisualTreeHelper
       return visualTreeHelper.GetParent(child);
   }
}

public interface IVisualTreeHelper
{
    DependencyObject GetParent(DependencyObject reference);
}

public class FrameworkVisualTreeHelper : IVisualTreeHelper
{
    public DependencyObject GetParent(DependencyObject reference)
    {
        return VisualTreeHelper.GetParent(reference);
    }
}

显然,如果您在其他地方使用其他方法,则可能需要将其他 VisualTreeHelper 方法添加到您的接口和默认实现中。

它仍然不完全干净,因为您正在测试的单元本身是静态的,当您尝试对依赖于 UIHelper 类的静态方法的任何类进行单元测试时,您将遇到完全相同的问题。

This is why statics are problematic.

You can abstract the functionality behind an interface and create a default implementation that uses the static method. You can then use dependency injection, which makes this unit test trivial -- mock the dependency on IVisualTreeHelper or roll your own stub implementation that you can configure to return any value you assign.

public class Foo
{
    static IVisualTreeHelper visualTreeHelper;

    static Foo()
    {
        Foo.visualTreeHelper = new FrameworkVisualTreeHelper();
    }

    public Foo(IVisualTreeHelper visualTreeHelper)
    {
        Foo.visualTreeHelper = visualTreeHelper;
    }

    public static DependencyObject GetParentObject(DependencyObject child)
   {
       if (child == null) return null;
       ContentElement contentElement = child as ContentElement;

       if (contentElement != null)
       {
           var parent = ContentOperations.GetParent(contentElement);
           if (parent != null) return parent;

           var fce = contentElement as FrameworkContentElement;
           return fce != null ? fce.Parent : null;
       }

       //if it's not a ContentElement, rely on the IVisualTreeHelper
       return visualTreeHelper.GetParent(child);
   }
}

public interface IVisualTreeHelper
{
    DependencyObject GetParent(DependencyObject reference);
}

public class FrameworkVisualTreeHelper : IVisualTreeHelper
{
    public DependencyObject GetParent(DependencyObject reference)
    {
        return VisualTreeHelper.GetParent(reference);
    }
}

Obviously, you may need to add other VisualTreeHelper methods to your interface and default implementation, if you're using other methods elsewhere.

It is still not completely clean because the unit you're testing is itself static, and you're going to run into exactly the same problem when you try to unit test any class that relies on your UIHelper class' static methods.

2024-10-11 07:33:07

要模拟可视化树,您必须实际创建并渲染一棵可视化树。因此,您必须创建一个实际的窗口,这对于单元测试来说并不是特别理想。

To mock a visual tree you will have to actually create and render one. So you will have to create an actual window, wich isn't particulary ideal for a unit test.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文