How to write Testcases with ServiceProvider.GetKeyedService method in .Net 8?

DI Registeration services.AddKeyedTransient<IReceivableDocument,BuyerReceivableDocumentStrategy>(ReceivableCompanyType.Buyer); services.AddKeyedTransient<IReceivableDocument,AuctionReceivableDocumentStrategy>(ReceivableCompanyType.Auction); Class using Service public class TestReceivableCommandHandler(IServiceProvider receivableDocumentResolver) : IRequestHandler<CreateReceivableCommand, Result<Unit, ValidationException>> { public async Task<Result<Unit, ValidationException>> Handle(CreateReceivableCommand request, CancellationToken cancellationToken) { var receivableStrategy = receivableDocumentResolver.GetRequiredKeyedService<IReceivableDocument>( (ReceivableCompanyType)request.CustomerTypeID); return Result<Unit, ValidationException>.SucceedWith(Unit.Value); } } While running unit test cases, I am getting below error It seems we can not moq Extension methods. if it is case, how we can unit test any KeyedService registration? Unsupported expression: a => a.GetKeyedService<IReceivableDocument>((object)It.IsAny<ReceivableCompanyType>()) Extension methods (here: ServiceProviderKeyedServiceExtensions.GetKeyedService) may not be used in setup / verification expressions.
3 Replies
Davaaron
Davaaron7mo ago
How about mocking the IServiceProvider?
Pobiega
Pobiega7mo ago
They can't, since the method in question is an extension method. Instead, set up an actual service collection for your test case One that contains the keyed service, with the right key Or rather, the correct interface, but points to the mocked instance
Sagar viradiya
Sagar viradiyaOP7mo ago
Not following, can you provide example. I think there should be proper documentation. as it is need for simple case.
Want results from more Discord servers?
Add your server