How to use moq to verify that a similar object was passed in as argument?

The following should work for you:

Moq.It.Is<Account>(a=>a.Property1 == _account.Property1)

However as it was mentioned you have to implement matching criteria.


To stub out a repository to return a particular value based on like criteria, the following should work:

_repositoryStub
    .Setup(x => x.Create(
        Moq.It.Is<Account>(a => _maskAccount.ToExpectedObject().Equals(a))))
    .Returns(_account);

I have done that using the FluentAssertians library (which is much more flexible and has lot's of goodies), as in the following example:

_mockedRepository
        .Setup(x => x.Create(Moq.It.Is<Account>(actual =>
                   actual.Should().BeEquivalentTo(_account, 
                       "") != null)))
        .Returns(_account);

Note the empty argument, which is needed since this is a lambda expression which can't use default parameters.

Also note the != null expression which is just to convert it to bool so to be able to compile, and to be able to pass when it is equal, since when it is not equal then FluentAssertians will throw.


Note that this only works in newer versions of FluentAssertians, for older versions you can do a similar method described in http://www.craigwardman.com/Blogging/BlogEntry/using-fluent-assertions-inside-of-a-moq-verify

It involves using an AssertionScope as in the following code

public static class FluentVerifier
{
    public static bool VerifyFluentAssertion(Action assertion)
    {
        using (var assertionScope = new AssertionScope())
        {
             assertion();

             return !assertionScope.Discard().Any();
        }
    }
 }

And then you can do:

_mockedRepository
            .Setup(x => x.Create(Moq.It.Is<Account>(actual => 
                   FluentVerifier.VerifyFluentAssertion(() =>
                       actual.Should().BeEquivalentTo(_account, "")))))))
            .Returns(_account);