No invocation for Moq when using short action call syntax in ForEach method

64 Views Asked by At

I encountered a strange difference in how Moq behaves when verifying that a method is called.

The verification

supportMock.Verify(m => m.Insert(It.IsAny<MyEntity>()));

Working code (when being tested with the verification code)

toInsert.ForEach(e => repo.Insert(e));

Non-working code (when being tested with the verification code)

toInsert.ForEach(repo.Insert);

Moq.MockException: ' Expected invocation on the mock at least once, but was never performed: m => m.Insert(It.IsAny(), [])

Performed invocations:

MockMyEntityRepository:1 (m): {other invocation to delete removed for brevity}

RepositoryTranslatable<MyEntity, Translation>.Insert(MyEntity) RepositoryTranslatable<MyEntity, Translation>.Insert(MyEntity) RepositoryTranslatable<MyEntity, Translation>.Insert(MyEntity) '

ForEach code (from net45\Microsoft.Practices.Unity.dll)

public static void ForEach<TItem>(this IEnumerable<TItem> sequence, Action<TItem> action)
{
  Guard.ArgumentNotNull((object) sequence, nameof (sequence));
  foreach (TItem obj in sequence)
    action(obj);
}

There seems to be a subtle difference in how Moq treats those calls which have the same effect when running the code outside of unit testings.

What is the difference between those two ways of writing the same code?

0

There are 0 best solutions below