chevron-thin-right chevron-thin-left brand cancel-circle search youtube-icon google-plus-icon linkedin-icon facebook-icon twitter-icon toolbox download check linkedin phone twitter-old google-plus facebook profile-male chat calendar profile-male
0 votes
Hi,

Assume I have the following method to mock :

Class A
{
int Foo(delegate del)
{
....
}
}

Class B
{
void Bb()
{
...
}
}

On the testing code, how can I expect the A.Foo to be called with a specific delegate B.Bb delegate as parameter ?

Thanks in advance.
asked by niluje (600 points)

1 Answer

0 votes
Hi,

Here's a bit of code on how to do this:
        [TestMethod, VerifyMocks]
        public void TestDelegate()
        {
            ClassA.ParamDelegate mydelegate = new ClassA.ParamDelegate(ClassB.SecondMethod);

            using (RecordExpectations rec = RecorderManager.StartRecording())
            {
                ClassA mockA = new ClassA();
                mockA.Foo(null);
                rec.CheckArguments(mydelegate);
            }

            ClassA a = new ClassA();
            
            // This passes
            a.Foo(mydelegate); 
            
            // This fails because of the argument check.
            a.Foo(new ClassA.ParamDelegate(ClassB.FirstMethod));
        }
    }

    public class ClassA
    {
        public delegate void ParamDelegate();
       
        public void Foo(ParamDelegate del)
        {

        }
    }

    public class ClassB
    {
        public static void FirstMethod()
        {

        }
        public static void SecondMethod()
        {

        }
}


Note the two different cases, and how to use CheckArguments to validate the correct delegate is sent.
answered by gilz (14.5k points)
...