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

Improve a exception message for extension methods. #1305

Closed
motz-art opened this issue Dec 2, 2022 · 3 comments
Closed

Improve a exception message for extension methods. #1305

motz-art opened this issue Dec 2, 2022 · 3 comments

Comments

@motz-art
Copy link

motz-art commented Dec 2, 2022

Steps to reproduce

Trying to mockick IMemoryCache like this:

    var mock = new Mock<IMemoryCache>();
    var value = "Test Value";
    mock.Setup(x => x.TryGetValue(Key, out value)).Returns(true);

Actual result:

System.NotSupportedException : Unsupported expression: x => x.TryGetValue<string>("Test", value)

Expected result:

System.NotSupportedException : Can't mock call to CacheExtensions.TryGetValue extension method.

The issue is that this extension method has same name and parameters set as the one from the interface and it's not clear what's wrong with Setup when just looking into the code.

@stakx
Copy link
Contributor

stakx commented Dec 5, 2022

I agree that the suggested error message would be more helpful than the current one. Feel free to submit a PR. Extra points if the code generating the error message can be set up in such a way that we can easily extend it to also provide a descriptive error for other types of non-overridable methods (e.g. static or sealed methods).

@motz-art
Copy link
Author

motz-art commented Dec 7, 2022

After trying to implement it, I have found the Quard.IsOverridable(MethodInfo method, Expression expression) method and realized I didn't noticed a seccond line of the message with a hint.

So Actual result I have mentioned in the issue should be like this:

System.NotSupportedException: Unsupported expression: x => x.TryGetValue<string>("Test", value)
Extension methods (here: CacheExtensions.TryGetValue) may not be used in setup / verification expressions.

I'm sorry for submitting the issue.

@motz-art motz-art closed this as completed Dec 7, 2022
@stakx
Copy link
Contributor

stakx commented Dec 7, 2022

I am glad you found this out. I vaguely remembered that we already have a more precise exception message re: extension methods somewhere but I didn't realise it would show up in your scenario.

All good & no worries.

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

No branches or pull requests

2 participants