Search code examples
c#unit-testingrhino-mocks

Rhino Mocks, assert that a MockRepository was not used (methods)?


Is there a way of asserting that no methods were called in MockRepository?

Say I have:

var repo = MockRepository.GenerateStub<RealRepo>();

I know I can do:

repo.AssertWasNotCalled(...);

But is there a way of checking that it was not used? Instead of doing all the methods everytime i want to check if a repo was not used?

I have cases where I want to just check that I don't use this repo.


Solution

  • You can try adding your own extension to Rhino Mocks. Something like this:

        public static void AssertNothingWasCalled<T>(this T mock)
        {
            var methodsToVerify = typeof (T)
                .GetMethods()
                .Where(m => !m.IsSpecialName);
    
            foreach (var method in methodsToVerify)
            {
                var arguments = BuildArguments(method);
                var action = new Action<T>(x => method.Invoke(x, arguments));
                mock.AssertWasNotCalled(action, y => y.IgnoreArguments());
            }
        }
    
        private static object[] BuildArguments(MethodInfo methodInfo)
        {
            return methodInfo
                .GetParameters()
                .Select(p => Arg<object>.Is.Anything)
                .ToArray();
        }
    

    But the answer by Sergey Berezovskiy seems a bit simpler.