views:

307

answers:

1

I have a method that performs an asynchronous service call. I call this class by passing in the callback.

public void GetRights(EventHandler<GetRightsCompletedEventArgs> callback)
{
    ServiceClient client = new ServiceClient();
    client.GetRightsCompleted += new EventHandler<GetRightsCompletedEventArgs>(callback);
    client.GetRightsAsync();
}

GetRights(GetRightsCallback);

I'm creating tests with MSTest, and I've mocked the containing class (IGetRightsProxy) in Moq. How can I invoke the callback when this method is called in the test?

GetRightsForCurrentUserCompletedEventArgs results = 
    new GetRightsCompletedEventArgs(
    new object[] { new ObservableCollection<Right>()}, null, false, null);
Mock<IGetRightsProxy> MockIGetRightsProxy = new Mock<GetRightsProxy>();
A: 

One way of doing what I want is to extend the class like this:

class MockGetRightsProxy : IGetRightsProxy
{
    public void GetRights(EventHandler<GetRightsCompletedEventArgs> callback)
    {
        // Create some args here
        GetRightsCompletedEventArgs args = new GetRightsCompletedEventArgs(
            new object[] { new ObservableCollection<Right>() }, null, false, null);

        callback(null, args);
    }

}

I was looking for ways to invoke the callback in Moq, but this works, too.

Rachel Martin