-2

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

Jissai
  • 1
  • 2
  • Why you are casting your class as dynamic you know what the dynmic used for?! – Bassam Alugili May 13 '14 at 08:25
  • Did any answer solved your problem? then please mark it! – Bassam Alugili May 13 '14 at 08:32
  • `dynamic t = _m.Object;` shouldn't be in the question. Sorry for that, it was from one of my previous attempts. – Jissai May 13 '14 at 08:45
  • `dispatch(_m.Object);` works just fine. – abto May 13 '14 at 08:54
  • Can you please reassure (re-test) that a simple replace of `Test ts = _m.Object; dispatch(ts);` by `dispatch(_m.Object);` really leads to the exception? I find this hard to believe. – chiccodoro May 13 '14 at 08:55
  • before you edited your question I could have seen the source of the exception. After your edit it is not visible anymore. Before your edit you were in fact calling `.Object` on `.Object`. – chiccodoro May 13 '14 at 08:56
  • Now it works fine in unit-testing. You'are right... still not working in my code, i wil investigate more. – Jissai May 13 '14 at 09:01

1 Answers1

1

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

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

mathk
  • 7,973
  • 6
  • 45
  • 74
  • Because without the call to `.Object` the instance is `Mock` not a `Test` and `dispatch()` handles only `Test` – Jissai May 13 '14 at 08:51
  • @Jissai in your first version of your post you did `t = _m.Object` therefore `t` **was** of type `Test` which did not have an `Object` property. – abto May 13 '14 at 08:58
  • This answer was the closest to real source of my problem as i was doing an extra `dynamic t = _m.Object;` wich lead me to wrongly call dispatch(t.Object) instead of dispatch(_m.Object). But the answer was a bit cryptic for me at once :) Thank you abto and chiccodoro for the explanations. – Jissai May 13 '14 at 09:10