4

I have a class implementation as below. MethodUnderTest() is the method which calls the delegate to update grid with some custom filter, with a callback function - UpdateGridCallback.

public class MyClass
{
    public delegate void UpdateGridDelegate(MyCustomFilters filter);
    public UpdateGridDelegate del;
    public MyCustomFilters filter;

    public void MethodUnderTest()
    {
        //.... some code...
        // For simplicity of example I am passing somename.. should be passing rows..

        // set status bar saying retriving data..

       del = new UpdateGridDelegate(UpdateGrid);
       del.BeginInvoke(filter, UpdateGridCallback, null);
    }

    public void UpdateGrid(MyCustomFilters filter)
    {
       // Upadte Grid with passed rows.
    }

    public void UpdateGridCallback(IAsyncResult result)
    {
       // callback .. do some action here.. like updating status bar saying - Ready
    }
}

I am using Nunit and Moq.delegate. MethodUnderTest() is the method under test. How do I mock the delegate which is being used in MethodUnderTest()?

I want to make sure that delegate was invoked (or callback was executed) from my NUnit test case.

bvishy
  • 41
  • 2

1 Answers1

3

You can't mock it as long as you new it up inside MethodUnderTest. You can only mock what you could also have written by hand, but in this case, there's no way to get at del from the outside.

You'll need to change the design to pass it in from the outside. Since del is already a class field, it seems most natural to pass it via Constructor Injection:

public class MyClass
{
    public delegate void UpdateGridDelegate(MyCustomFilters filter);
    public UpdateGridDelegate del;
    public MyCustomFilters filter;

    public MyClass(UpdateGridDelegate del)
    {
        this.del = del;
    }

    // etc.
}

Now you can mock it.

Community
  • 1
  • 1
Mark Seemann
  • 225,310
  • 48
  • 427
  • 736