如何在使用Moq的测试中引发事件?
这是父类中代码实现的一部分:
Here is part of code implementation in parent class:
handler.FooUpdateDelegate += FooUpdate(OnFooUpdate);
protected abstract void OnFooUpdate(ref IBoo boo, string s);
我在测试方法中有模拟处理程序:
I have in test method mocked handler:
Mock<IHandler> mHandler = mockFactory.Create<IHandler>();
这个...
mHandler.Raise(x => x.FooUpdateDelegate += null, boo, s);
...不起作用.它说:
...is not working. It says:
System.ArgumentException:无法找到附加或分离方法Void set_FooUpdateDelegate(FooUpdate)的事件.
System.ArgumentException : Could not locate event for attach or detach method Void set_FooUpdateDelegate(FooUpdate).
我想提高OnFooUpdate
,以便触发要在子类中测试的代码.
I want to raise OnFooUpdate
so it triggers the code to be tested in child class.
问题:如何使用Moq引发委托(不是公共事件处理程序)?
Question: How can I raise delegate (not common event handler) with Moq?
如果我完全错过了重点,请让我合格.
If I missed the point completely, please enligten me.
您似乎正在尝试引发一个委托而不是一个事件.是这样吗?
It looks like you are trying to raise a delegate rather than an event. Is this so?
您的代码是否与此相符?
Is your code along the lines of this?
public delegate void FooUpdateDelegate(ref int first, string second);
public class MyClass {
public FooUpdateDelegate FooUpdateDelegate { get; set; }
}
public class MyWrapperClass {
public MyWrapperClass(MyClass myclass) {
myclass.FooUpdateDelegate += HandleFooUpdate;
}
public string Output { get; private set; }
private void HandleFooUpdate(ref int i, string s) {
Output = s;
}
}
如果是这样,那么您可以像这样直接调用myClass FooUpdateDelegate
If so, then you can directly invoke the myClass FooUpdateDelegate like so
[TestMethod]
public void MockingNonStandardDelegate() {
var mockMyClass = new Mock<MyClass>();
var wrapper = new MyWrapperClass(mockMyClass.Object);
int z = 19;
mockMyClass.Object.FooUpdateDelegate(ref z, "ABC");
Assert.AreEqual("ABC", wrapper.Output);
}
使用界面添加版本
public interface IMyClass
{
FooUpdateDelegate FooUpdateDelegate { get; set; }
}
public class MyClass : IMyClass {
public FooUpdateDelegate FooUpdateDelegate { get; set; }
}
public class MyWrapperClass {
public MyWrapperClass(IMyClass myclass) {
myclass.FooUpdateDelegate += HandleFooUpdate;
}
public string Output { get; private set; }
private void HandleFooUpdate(ref int i, string s) {
Output = s;
}
}
[TestMethod]
public void MockingNonStandardDelegate()
{
var mockMyClass = new Mock<IMyClass>();
// Test fails with a Null Reference exception if we do not set up
// the delegate property.
// Can also use
// mockMyClass.SetupProperty(m => m.FooUpdateDelegate);
mockMyClass.SetupAllProperties();
var wrapper = new MyWrapperClass(mockMyClass.Object);
int z = 19;
mockMyClass.Object.FooUpdateDelegate(ref z, "ABC");
Assert.AreEqual("ABC", wrapper.Output);
}