Unit Testing IServiceCollection Registration

时光毁灭记忆、已成空白 提交于 2019-12-30 17:25:48

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/51180523/unit-testing-iservicecollection-registration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!