Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is why statics are problematic. </p> <p>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.</p> <pre><code>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); } } </code></pre> <p>Obviously, you may need to add other <code>VisualTreeHelper</code> methods to your interface and default implementation, if you're using other methods elsewhere.</p> <p>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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload