Unit testing with mock framework and IEquatable<>

This post is relevant for the one’s who write tests, all you other programmers, you should learn unit testing and read it. One of the most useful tools in unit testing is a good mocking framework. (I’m currently using Moq, and before that I used rhino) We all know that for mocking we need interfaces. My tip is very simple, if you have a class Foo and you wanna mock it, first you should have Interface IFoo (this should be obvious to most of you).Implement on Foo IEquatable<IFoo>, so if you test a list of IFoo and you want to assert Contains() you won’t have any problems with the proxy of IFoo that mocking framework generates on the interface and no one will blame you for your awful class that throws cast exception in its equals method :). Hope it’ll save you time in future. That it, KIS.

November 17, 2010 · 1 min · Chen Kinnrot

Unit Test PropertyChanged

One of the basic stuff you wanna test as a client side developer, is that all of your UI bounded classes aka Controller, Model, ViewModel, Presenter, PresentationModel, or the code behind of your view if your just having fun. Let’s assume we have a person class with a name property: public class Person : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private string _name; public virtual string Name { get { return _name; } set { _name = value; FirePropertyChanged(“Name”); } } protected virtual void FirePropertyChanged(string propertyName) { var handlers = PropertyChanged; if (handlers != null) { handlers(this, new PropertyChangedEventArgs(propertyName)); } } } The simplest way to perform this test is to write this code: [TestFixture] public class PersonTest { [Test] public void SetName_SomeNewString_FirePropertyChanged() { Person person = new Person(); string changedPropertyName = string.Empty; person.PropertyChanged += (sender, args) => changedPropertyName = args.PropertyName; person.Name = “Test”; Assert.AreEqual(“Name”, changedPropertyName); } }

September 1, 2010 · 1 min · Chen Kinnrot