Listing 1 – INotifyPropertyChanged Interface
Listing 2 – IEntity Interface and BaseEntity base class
Property getters are mocked the same way traditional methods are mocked (minus the parenthesis and parameters, of course!). To show this in action, I’ve created a simple implementation of an ICommand. For those of you familiar with XAML, this is old hat. If you aren’t a familiar with the ICommand pattern, it works like this:
Of course, there’s a lot more to it than that, but that’s enough for what we are testing. The implementation of ICommand is shown in Listing 3.
Listing 4 – Mocking the getter for a property
Listing 5 – Demonstration Test for Mock.ArrangeSet
The real need for this type of test is to test our implementation of OnPropertyChanged. Remember that the INotifyPropertyChanged mechanism raises an event whenever a value changes on the class the implements the interface? Well, it doesn’t happen for free. It has to be coded. And if not coded correctly, the benefit of the pattern will be lost. A typical implementation that I use when developing XAML based applications is shown in Listing 6. The BaseEntity is the core functionality with the implementation of the IEntity interface (which contains the INotifyProertyChanged interface as well as the IsDirty property) and the OnPropertyChanged method, which set’s the IsDirtyFlag to true. What’s missing is the call to raise the PropertyChanged event, which I omitted for brevity.
Listing 6 – Base Entity and a Customer Entity
Listing 7 – Testing the IsDirty setter
Philip Japikse is an international speaker, a Microsoft MVP, ASPInsider, INETA Community Champion, MCSD, CSM/ CSP, and a passionate member of the developer community. Phil has been working with .Net since the first betas, developing software for over 20 years, and heavily involved in the agile community since 2005. Phil also hosts the Hallway Conversations podcast (www.hallwayconversations.com) and serves as the Lead Director for the Cincinnati .Net User’s Group (http://www.cinnug.org). You can follow Phil on twitter via www.twitter.com/skimedic, or read his personal blog at www.skimedic.com/blog.
Subscribe to be the first to get our expert-written articles and tutorials for developers!