What is the best practice to check if an object is changed?
.net, c#
Solution
When I need to track changes to properties on my objects for testing I hook an event handler on the objects PropertyChanged event. Will that help you? Then your tests can do whatever action they want based on the change. Normally I count the number of changes, and add the changes to dictionaries, etc.
To achieve this your class must implement the INotifyPropertyChanged interface. Then anyone can attach and listen to changed properties:
public class MyClass : INotifyPropertyChanged { ... }
[TestFixture]
public class MyTestClass
{
private readonly Dictionary<string, int> _propertiesChanged = new Dictionary<string, int>();
private int _eventCounter;
[Test]
public void SomeTest()
{
// First attach to the object
var myObj = new MyClass();
myObj.PropertyChanged += SomeCustomEventHandler;
myObj.DoSomething();
// And here you can check whether the object updated properties - and which -
// dependent on what you do in SomeCustomEventHandler.
// E.g. that there are 2 changes - properties Id and Name changed once each:
Assert.AreEqual(2, _eventCounter);
Assert.AreEqual(1, _propertiesChanged["Id"]);
Assert.AreEqual(1, _propertiesChanged["Name"]);
}
// In this example - counting total number of changes - and count pr property.
// Do whatever suits you.
private void SomeCustomEventHandler(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
var property = e.PropertyName;
if (_propertiesChanged.ContainsKey(property))
_propertiesChanged[property]++;
else
_propertiesChanged[property] = 1;
_eventCounter++;
}
}
Problem
I need to know how do you check if an object is changed. Basically I need something like a property that is named TrackChanges, when I set it true once and if any data within this object is "changed", a method on the same object (IsObjectChanged) can return true. Did you ever needed such a thing and how did you solve it? I do not want to invent the wheel if there is already a best-practice for such scenario? I was thinking to clone the object before I call TrackChange=true, in its setter. And when I call IsObjectChanged() By using reflection I will compare all the public field values of it with the cloned copy. I am not sure if it is a good way. Any advices? thanks, burak ozdogan