简体   繁体   中英

Unit Testing Dependency Properties

I have inherited some existing projects where the developer was using Dependency properties rather that INotifyPropertyChanged for WPF change notification.

I am in a position where I need to retro-fit unit tests to the entire solution.

Some of the dependency properties in the ViewModel get directly updated asynchronously from some background worker process, so I need to hook into these updates via my unit tests. (I cannot changed the code and use callbacks).

How can this be achieved ?

A lot of developers seem to favor dependency properties over INotifyPropertyChanged , but they seem very difficult (if not impossible) to write unit tests for.

Am I missing something ?

You can use DependencyPropertyDescriptor to attach a changed handler to a dependency property:

DependencyPropertyDescriptor.FromProperty(TextBox.TextProperty, typeof(TextBox)).AddValueChanged(textBox, OnTextChanged);

However, there are a slew of reasons not to use dependency properties in your view models. Given that you've inherited the code, I would suggest writing unit tests to assert the behavior of the code and then switching over to use INotifyPropertyChanged .

Since dependency properties can controlled in xaml, there may not be a good way to comprehensively unit test them without launching any windows that are using them. At which point you're really not unit testing anymore.

That said, you can go after the dependency property by calling the DependencyObject 's GetValue() and SetValue() methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM