提高
的提高
方法用于引发模拟事件。您可以使用自定义事件或标准事件。
引发自定义事件
假设我们有以下接口:
public delegate void CustomEvent(string value);公共接口IFoo{事件CustomEvent CustomEvent;}
公共代理子CustomEvent(value As String)公共接口IFoo事件CustomEvent作为CustomEvent结束接口
下面是如何使用的例子提高
触发自定义事件。
[TestMethod] public void ShouldInvokeMethodForACustomEventWhenRaised() {string expected = "ping";string actual = string. empty;//安排var foo = Mock.Create();foo。CustomEvent += delegate(string s) {actual = s;};// Act Mock.Raise(() => foo。CustomEvent+= null, expected); // Assert Assert.AreEqual(expected, actual); }
Public Sub ShouldInvokeMethodForACustomEventWhenRaised() Dim expected As String = "ping" Dim actual As String = String。Empty ' Arrange Dim foo = Mock。Create(Of IFoo)() AddHandler foo。CustomEvent, Sub(s As String) actual = s ' Act Mock.Raise(Sub() AddHandler foo.CustomEvent, Nothing, expected) ' Assert Assert.AreEqual(expected, actual) End Sub
我们使用提高
提高foo。CustomEvent
然后传递"ping"给它。在行动之前,我们给事件附加了一个代表。执行委托将导致将传递的字符串分配给实际
。最后,我们验证一下预期
和实际
具有相同的值。
提高标准事件
假设我们正在测试以下系统:
IExecutor {event eventandler Done;}公共类FooArgs: EventArgs{公共FooArgs(){}公共FooArgs(字符串值){这个。Value = Value;}公共字符串值{get;设置;}}
结束接口公共类FooArgs继承EventArgs Public Sub New() End Sub Public Sub New(value As String) Me。End Sub - Public Property Value() As String Get Return m_Value End Get Set(Value As String) m_Value = Value End Set End Property Private m_Value As String End Class
一个关于如何使用的例子提高
要触发标准事件,看起来像这样:
[TestMethod] public void ShouldRaiseEventWithStandardEventArgs() {string actual = null;String expected = "ping";//安排var executor = Mock.Create>();遗嘱执行人。完成+= delegate(object sender, FooArgs args) { actual = args.Value; }; // Act Mock.Raise(() => executor.Done += null, new FooArgs(expected)); // Assert Assert.AreEqual(expected, actual); }
Public Sub ShouldRaiseEventWithStandardEventArgs() Dim actual As String = Nothing Dim expected As String = "ping" ' Arrange Dim executor = Mock。Create(Of IExecutor(Of Integer))() AddHandler executor。完成, Sub(sender As Object, args As FooArgs) actual = args.Value ' Act Mock.Raise(Sub() AddHandler executor.Done, Nothing, New FooArgs(expected)) ' Assert Assert.AreEqual(expected, actual) End Sub
这里我们使用提高
引起一个标准事件-遗嘱执行人。完成
接受FooArgs
对象。附加的委托设置价值
财产FooArgs
对象转换为变量实际
。最后,我们验证一下预期
和实际
具有相同的值。