Search code examples
c#unit-testingdependency-injection.net-core

Unit Testing IServiceCollection Registration


I'm trying to figure out the easiest way to test my Service Registrations method for my framework. I'm creating dynamic services my registration looks like so:

var messageHubConfig = new DynamicHubServiceConfiguration<Message, MessageDTO>();
messageHubConfig.SetDynamicHubOptions<AstootContext>(async (context, dto) =>
{
    return await context.ConversationSubscriptions
                        .Where(x => x.ConversationId == dto.ConversationId 
                               && x.IsSubscribed)
                        .Distinct()
                        .Select(x => x.User.UniqueIdentifier)
                        .ToListAsync();
});

messageHubConfig.RequiresDynamicValidator = false;
messageHubConfig.EventMapping.AddCreateEvent(async (sp, obj, dto) =>
{
    var conversationService = sp.GetService<IRestEzService<Conversation, ConversationDTO>>();
    var conversationDTO = await conversationService.Get(new object[] { dto.ConversationId });
    var hubTaskQueue = sp.GetService<IHubServiceTaskQueue>();
    hubTaskQueue.QueueDynamicCreate(conversationDTO);
}).When(async (sp, dto) => {
    var context = sp.GetService<AstootContext>();
    return await context.Conversations.Where(x => x.Id == dto.ConversationId).Where(x => x.Messages.Count == 1).AnyAsync();
});

//Registers service with a hub
restConfiguration.RegisterRestService(typeof(IMessageDTOService), 
                                      typeof(MessageDTOService), 
                                      messageHubConfig);

Inside of my Register Rest Service Method I have a lot of different services Getting registered e.g:

services.AddTransient(restServiceType, (IServiceProvider serviceProvider) =>
{
    var restService = (IRestEzService<TEntity, TDTO>)
        ActivatorUtilities.CreateInstance(serviceProvider, restServiceImplementationType);
    serviceOption.EventMapping?.Register(serviceProvider, restService);

    return restService;
});

How can I be assure that my factory configuration is being registered properly, How can I create a Service Collection for testing?


Solution

  • Create a ServiceCollection,

    var services = new ServiceCollection();
    

    call your registration function and then assert that your restServiceType was added.

    Next build a provider from the service collection, resolve the restServiceType

    var provider = services.BuildServiceProvider();
    var restService = provider.GetRequiredService(restServiceType);
    

    and assert that it is created as desired.

    The GetRequiredService extension method will throw an exception if the service is unable to resolve the target type.

    Now that is based solely on what is currently being shown in your example as I am unaware of any other dependencies.