I am working on a project using dynamic dispatch. While unit testing some of my methods with Moq, I stumbled on something I don't understand.

I tried to reproduce it on the test below :

public class UnitTest1
{
    [TestMethod]
    public void TestMethod1()
    {
        Mock<Test> _m = new Mock<Test>();

        //if i do
        //dispatch(_m.Object); //this line causes Exception

        //Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 
        //'Castle.Proxies.TestProxy' doesn't contain définition for 'Object'

        //but if i do
        Test ts = _m.Object;
        dispatch(ts); //this line works fine

        //verify
        _m.Verify(m => m.Display(), Times.Once());
    }

    public void dispatch(Test p)
    {
        p.Display();
    }
}

public interface Test
{
    void Display();
}

}

Can someone please explain me why it doesn't work without the cast to Test ? How can I unit-test dynamic dispatch without the casting ? (It is impossible in the code... hence why we use dynamic dispatching)

Thank you

有帮助吗?

解决方案

Why are you calling dispatch(t.Object); you should have call dispatch(t);

dynamic is just a way to turn off the type checker.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top