如何为触发的事件编写单元测试? [英] How Do I Write A Unit Test For An Event Being Triggered?
本文介绍了如何为触发的事件编写单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个类,当它的内部状态发生变化时会引发一个偶数(大致类似于INotifyPropertyChange但略有不同)。
我应该如何编写单元测试验证此事件确实已经提出?
(事件中ExpectedException与模型相同?)
I have a class that raises an even when its internal state changes (broadly similar to INotifyPropertyChange but slightly different).
How should I write a unit test that verifies that this event is indeed raised?
(There's nothing in the same model as "ExpectedException" for events?)
推荐答案
你好,
您可以在单元测试中使用代表来完成。
例如:
Hello,
You could do it using delegates in your unit tests.
for example:
[TestMethod]
public void EventShouldBeRaised()
{
ClassToTest classToTest = new ClassToTest();
bool eventRaised = false;
classToTest.EventRaised += delegate(object sender, ClassToTestEventArgs e)
{
eventRaised = true;
};
classToTest.Property1 = "somthing";
// this property raises an event, test if the boolean is set to true in the delegate call.
Assert.AreEqual(eventRaised, true);
}
[TestMethod]
public void EventShouldNotBeRaised()
{
ClassToTest classToTest = new ClassToTest();
bool eventRaised = false;
classToTest.EventRaised += delegate(object sender, ClassToTestEventArgs e)
{
eventRaised = true;
};
classToTest.AnotherProperty = "somthing";
// This property does not raise the event, so we test that the eventRaised boolean is false.
Assert.AreEqual(eventRaised, false);
}
Valery。
Valery.
这篇关于如何为触发的事件编写单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文