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

Extension methods (here: ServiceProviderServiceExtensions.GetRequiredService) may not be used in setup / verification expressions. #1171

Closed
akshay-zz opened this issue Jun 17, 2021 · 1 comment

Comments

@akshay-zz
Copy link

akshay-zz commented Jun 17, 2021

Facing this issue when mocking GetRequiredService
Actual function

private readonly IServiceScopeFactory _provider;
using var scope = _provider.CreateScope();
var queueRepo = scope.ServiceProvider.GetRequiredService<IQueuedMailRepository>();
await queueRepo.Remove(queueEmailDetail.Id);

How I'm trying to mock the injection while testing.


var mockServiceFactory = new Mock<IServiceScopeFactory>();

var mockServiceProvider = new Mock<IServiceProvider>();
var mockServiceScope = new Mock<IServiceScope>();
var mockRepo = new Mock<IQueuedMailRepository>();

mockServiceFactory.Setup(x => x.CreateScope()).Returns(mockServiceScope.Object);
mockServiceScope.Setup(x => x.ServiceProvider).Returns(mockServiceProvider.Object);
mockServiceProvider.Setup(x => x.GetRequiredService<IQueuedMailRepository>()).Returns(mockRepo.Object);
// OR
mockServiceProvider.Setup(x => x.GetRequiredService(typeof(IQueuedMailRepository))).Returns(mockRepo.Object);

Getting following error at last line of mock at run time

Message: 
    System.NotSupportedException : Unsupported expression: x => x.GetRequiredService(Mailer.DataAccess.Contracts.IQueuedMailRepository)
    Extension methods (here: ServiceProviderServiceExtensions.GetRequiredService) may not be used in setup / verification expressions.
@stakx
Copy link
Contributor

stakx commented Jun 17, 2021

Yep, Moq doesn't support setting up extension methods, and there is nothing we can do to change that. You can only set up & verify overridable methods.

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