Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@9swampy
Forked from Seikilos/INPCTracer
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 9swampy/ac54ac0c74302abdb43d to your computer and use it in GitHub Desktop.
Save 9swampy/ac54ac0c74302abdb43d to your computer and use it in GitHub Desktop.
/// <summary>
/// Performs tracing of INotifyPropertyChange events
/// </summary>
public class INCPTracer
{
~INCPTracer()
{
Detach();
Clear();
}
public INCPTracer With(INotifyPropertyChanged notifier)
{
Detach();
Notifier = notifier;
Attach();
Clear();
return this;
}
public INCPTracer CheckThat(Action a)
{
a();
return this;
}
/// <summary>
/// Call this method multiple times if an action created multiple events. The order will be preserved
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="expression"></param>
public INCPTracer RaisedEvent<T>(Expression<Func<T>> expression)
{
if (expression == null)
{
throw new ArgumentNullException("expression");
}
var body = expression.Body as MemberExpression;
if (body == null)
{
throw new ArgumentException("The body must be a member expression");
}
if (EventPos >= RaisedEventList.Count)
{
throw new ArgumentException(string.Format("Expected event '{0}' but no more events left", body.Member.Name));
}
if (RaisedEventList[EventPos] != body.Member.Name)
{
throw new ArgumentException(string.Format("Event {0} was not at position {1}", body.Member.Name, EventPos));
}
++EventPos;
return this;
}
private void NotifierOnPropertyChanged(object sender, PropertyChangedEventArgs propertyChangedEventArgs)
{
RaisedEventList.Add(propertyChangedEventArgs.PropertyName);
}
protected void Detach()
{
if (Notifier != null)
{
Notifier.PropertyChanged -= NotifierOnPropertyChanged;
}
}
protected void Attach()
{
if (Notifier != null)
{
Notifier.PropertyChanged += NotifierOnPropertyChanged;
}
}
protected void Clear()
{
RaisedEventList.Clear();
EventPos = 0;
}
protected INotifyPropertyChanged Notifier;
protected IList<string> RaisedEventList = new List<string>();
protected int EventPos = 0;
}
[Test]
public void Test_Notify_Property_Changed_Fired()
{
var p = new Project();
var tracer = new INCPTracer();
// Check for one event
tracer.With(p).CheckThat(() => p.Active = true).RaisedEvent(() => p.Active);
// Check for exact order of two events
tracer.With(p).CheckThat(() => p.Path = "test").RaisedEvent(() => p.Path).RaisedEvent(() => p.Active);
}
@9swampy
Copy link
Author

9swampy commented Aug 27, 2014

I've created a full DLL sln/csproj at https://github.com/9swampy/InpcTracer

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment