RajOpteamix / moq

Automatically exported from code.google.com/p/moq
Other
0 stars 0 forks source link

Feature: Assert on parameters of recorded method invocations. #340

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
I've found that I often need to perform assertions on complex objects that were 
passed as parameters to mocked service classes.  Normally I would use Verify 
and simply specify the expected values, but in a complex object with no 
effective ToString() implementation this makes it difficult to identify which 
specific value of the complex object was off.

To solve this problem I tinkered with the Moq source and added a new class and 
interface returned by Verify which will allow callbacks to perform assertions 
on the actual recorded parameters which were passed to mocked methods.  This 
should in no way affect any existing usage of the Moq api.

Example:
        public interface ITestInterface
        {
            void StringAction(string str);
        }

            var mock = new Mock<ITestInterface>();

            mock.Object.StringAction("test");

            bool didAssert = false;
            mock.Verify(x => x.StringAction(It.IsAny<string>()))
                .Assert((string str) =>
                            {
                                Assert.Equal("test", str);
                                didAssert = true;
                            });

            Assert.True(didAssert);

I have attached a patch file including some quick unit tests.  Please let me 
know if you would like me to make some improvements.

Thanks,
Gordon

Original issue reported on code.google.com by meanmys...@gmail.com on 4 Apr 2012 at 10:35

Attachments:

GoogleCodeExporter commented 9 years ago
I had another thought about implementing this a different way.  The above would 
still work, but if I have Verify return a list of recorded invocations, then 
the end user would have more control over the order and manner in which they 
are replayed.  I have attached another patch file showing this other 
implementation.

I also renamed the "Assert" function to "Replay" because I feel that is more 
indicative of what it actually does.

Thanks,
Gordon 

Original comment by meanmys...@gmail.com on 5 Apr 2012 at 4:46

Attachments: