How to raise an event in a test using Moq?

Here is part of the code implementation in the parent class:

handler.FooUpdateDelegate += FooUpdate(OnFooUpdate);
protected abstract void OnFooUpdate(ref IBoo boo, string s);

I have a bullying method in the verification method:

Mock<IHandler> mHandler = mockFactory.Create<IHandler>();

It...

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

... does not work. It says:

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

I want to raise OnFooUpdateso that it runs the test code in a child class.

Question: How can I assemble a delegate (not a common event handler) using Moq?

If I completely missed the point, please enroll me.

+5
source share
1 answer

It looks like you are trying to raise a delegate, not an event. This is true?

Is your code line by line 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

[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:

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

}
+8

All Articles