Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Objects of anonymous types are not matched #552

Closed
stakx opened this issue Dec 12, 2017 · 1 comment
Closed

Objects of anonymous types are not matched #552

stakx opened this issue Dec 12, 2017 · 1 comment

Comments

@stakx
Copy link
Contributor

stakx commented Dec 12, 2017

Repro 1:

Quoting from the Stack Overflow question, "Moq a function with anonymous type" (see there for details):

I'm trying to mock this method

Task<TResult> GetResultAsync<TResult>(Func<string, TResult> transformFunc)

like this

iMock.Setup(m => m.GetResultAsync(It.IsAny<Func<string, object>>())).ReturnsAsync(new { isPair = false });

Moq never matches my GetResultAsync method with the parameters sent.

Repro 2:

Quoting from another Stack Overflow question, "Setup method with signature IList<T> Get<T>(Guid id, Expression<Func<EntityName, T>> selector)" (see there for details):

public interface IRepository
{
    IList<T> GetEntityFieldsById<T>(Guid id, Expression<Func<EntityClass, T>> selector);
}

...
var result = _repository.GetEntityFieldsById(id, x => new {x.StartDate, x.EndDate});

...

Test method UnitTestProject1.UnitTest1.TestMethod1 threw exception: Moq.MockException: IRepository.GetEntityFieldsById<<>f__AnonymousType02>(d1b3c6fb-5a5e-4f0a-9f68-191ca6a61bff,
x => new <>f__AnonymousType02(StartDate = x.StartDate, EndDate = x.EndDate)) invocation failed with mock behavior Strict. All invocations on the mock must have a corresponding setup.

@stakx
Copy link
Contributor Author

stakx commented Dec 15, 2017

When Moq looks for a setup matching the invocation, the invoked method's signature is compared with that of the set up method's (see this method). Return types must match exactly (see this line of code). So even though anonymous types are assignment-compatible with object, they are still a different type from object, so setups don't get matched.

I am not sure whether this can or should be fixed (probably not), but #343 might help.

Making this scenario work by relaxing Moq's method matching logic would be wrong. #343 is likely to be the solution for this problem, if one exists at all.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant