Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to raise an event in a test that uses 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>();

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.

like image 622
Adronius Avatar asked Aug 24 '12 11:08

Adronius


1 Answers

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

}
like image 194
AlanT Avatar answered Oct 11 '22 17:10

AlanT