Search code examples
unit-testingrhino-mocks

AssertWasCalled on dynamic in Rhino Mocks


Is there any way to do an AssertWasCalled on a dynamic in RhinoMocks, like this:

    var testObject = MockRepository.GenerateStub<dynamic>();
    testObject.AssertWasCalled(x=>x.MyMethod(Arg<string>.Matches(y=>y == "TestString"));

Solution

  • As I mentioned in my comments, I don't think most proxy based Mock object frameworks (RhinoMock/Moq) support dynamic verification. You may try a profiler based framework such as TypeMock etc, but they are not free.

    So the only option I think is to go back to old school where we wrote hand written stubs/mocks.

    Create another layer of indirection. A technique in many places describe as extract and override. So you simply create a hand written mock to verify this behaviour.

    a. Create a simple/silly protected virtual member which wraps your dynamic call

    System Under Test (SUT) :

      public class Sut {
        private dynamic _d;
    
        public Sut(dynamic d) {
            _d = d;
        }
    
        public void M() {
            MyMethod();
        }
    
        protected virtual void MyMethod() {
            _d.MyMethod();
        }
     }
    

    b. In your Unit Test, create a testable version of Sut by inheriting from Sut. Important : It should only contain the overridden method, but nothing else (except the bool to ensure the overridden method was called)

    public class TestableSutWithDynamic : Sut {
        public bool WasCalled = false;
    
        protected override void MyMethod() {
            WasCalled = true;
        }
    }
    

    c. Then simply assert against the testable Sut

        [Test]
        public void VerifyMyMethodIsCalled() {
            var sut = new TestableSutWithDynamic();
    
            sut.M();
    
            Assert.True(sut.WasCalled);
        }