我最近不得不这样做,下面是我想出的。我没有按照其他帖子所说的那样做的原因是,我不喜欢变量保持状态并且必须在多个事件之间“手动”重置它的想法。
下面是在MyTests 测试中测试的ClassUnderTest 和NameChanged 事件的代码:
public class ClassUnderTest {
private string name;
public string Name {
get { return this.name; }
set {
if (value != this.name) {
this.name = value;
NameChanged(this, new PropertyChangedEventArgs("Name"));
}
}
}
public event EventHandler<PropertyChangedEventArgs> NameChanged = delegate { };
}
[TestFixture]
public class MyTests {
[Test]
public void Test_SameValue() {
var t = new ClassUnderTest();
var e = new EventHandlerCapture<PropertyChangedEventArgs>();
t.NameChanged += e.Handler;
Event.Assert(e, Event.IsNotRaised<PropertyChangedEventArgs>(), () => t.Name = null);
t.Name = "test";
Event.Assert(e, Event.IsNotRaised<PropertyChangedEventArgs>(), () => t.Name = "test");
}
[Test]
public void Test_DifferentValue() {
var t = new ClassUnderTest();
var e = new EventHandlerCapture<PropertyChangedEventArgs>();
t.NameChanged += e.Handler;
Event.Assert(e, Event.IsPropertyChanged(t, "Name"), () => t.Name = "test");
Event.Assert(e, Event.IsPropertyChanged(t, "Name"), () => t.Name = null);
}
}
支持类如下。这些类可以与任何EventHandler<TEventArgs> 一起使用或扩展到其他代表。事件测试可以嵌套。
/// <summary>Class to capture events</summary>
public class EventHandlerCapture<TEventArgs> where TEventArgs : EventArgs {
public EventHandlerCapture() {
this.Reset();
}
public object Sender { get; private set; }
public TEventArgs EventArgs { get; private set; }
public bool WasRaised { get; private set; }
public void Reset() {
this.Sender = null;
this.EventArgs = null;
this.WasRaised = false;
}
public void Handler(object sender, TEventArgs e) {
this.WasRaised = true;
this.Sender = sender;
this.EventArgs = e;
}
}
/// <summary>Contains things that make tests simple</summary>
public static class Event {
public static void Assert<TEventArgs>(EventHandlerCapture<TEventArgs> capture, Action<EventHandlerCapture<TEventArgs>> test, Action code) where TEventArgs : EventArgs {
capture.Reset();
code();
test(capture);
}
public static Action<EventHandlerCapture<TEventArgs>> IsNotRaised<TEventArgs>() where TEventArgs : EventArgs {
return (EventHandlerCapture<TEventArgs> test) => {
NUnit.Framework.Assert.That(test.WasRaised, Is.False);
};
}
public static Action<EventHandlerCapture<PropertyChangedEventArgs>> IsPropertyChanged(object sender, string name) {
return (EventHandlerCapture<PropertyChangedEventArgs> test) => {
NUnit.Framework.Assert.That(test.WasRaised, Is.True);
NUnit.Framework.Assert.That(test.Sender, Is.SameAs(sender));
NUnit.Framework.Assert.That(test.EventArgs.PropertyName, Is.EqualTo(name));
};
}
}