How to raise an event in a test that uses Moq?

别等时光非礼了梦想. 提交于 2019-12-10 15:18:10

问题


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>();

This...

mHandler.Raise(x => x.FooUpdateDelegate += null, boo, s);

...is not working. It says:

System.ArgumentException : Could not locate event for attach or detach method Void set_FooUpdateDelegate(FooUpdate).

I want to raise OnFooUpdate so it triggers the code to be tested in child class.

Question: How can I raise delegate (not common event handler) with Moq?

If I missed the point completely, please enligten me.


回答1:


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;
    }

}

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);

}

EDIT: Adding version using interface

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);

}


来源:https://stackoverflow.com/questions/12108772/how-to-raise-an-event-in-a-test-that-uses-moq

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!