Home > database >  Cannot access method 'Handle' MediatR due to its protection level .net using xunit
Cannot access method 'Handle' MediatR due to its protection level .net using xunit

Time:01-12

I want to test a handler that is protected due to the AsyncRequestHandler interface in MediatR.Here is my handler :

public sealed class AddUserDeviceCommandHandler : AsyncRequestHandler<AddUserDeviceCommand>
{
    private readonly ICurrentUserService _userService;
    private readonly IRepository<UserDevice> _repository;

    public AddUserDeviceCommandHandler(ICurrentUserService userService, IRepositoryAccessor repositoryAccessor)
    {
        _userService = userService;
        _repository = repositoryAccessor.GetRepository<UserDevice>(_userService.CustomerIsin,
            reThrowException: true, type: DatabaseType.Raven);
    }

    protected override async Task Handle(AddUserDeviceCommand request, CancellationToken cancellationToken)
    {

        //do do do some code
        await _repository.AddOrUpdateAsync(model);
    }
}

As you can see the Handle method is protected .So in my test I can't access the handle method :

AddUserDeviceCommand command = new AddUserDeviceCommand(data.AppBuildNo,data.Width,data.Height,data.PlatformInfo,data.DevicePlatform);
        AddUserDeviceCommandHandler handler = new AddUserDeviceCommandHandler(userservice.Object, repoacc.Object);

        handler.?????

appreciate for any help

CodePudding user response:

Declare the handler variable as of type IRequestHandler<AddUserDeviceCommand>.

AsyncRequestHandler<TRequest> implements IRequestHandler<TRequest>, via which you can access its Handle method.

AddUserDeviceCommand command = new AddUserDeviceCommand(  
    ​data.AppBuildNo, data.Width, data.Height, data.PlatformInfo, data.DevicePlatform
    );
IRequestHandler<AddUserDeviceCommand> handler = new AddUserDeviceCommandHandler(
    userservice.Object, repoacc.Object
    );

await handler.Handle(command, CancellationToken.None);

CodePudding user response:

Reflection ...

MethodInfo method = handler
    .GetType()
    .GetMethod("Handle", BindingFlags.Instance | BindingFlags.NonPublic);

await (Task)method.Invoke(
    handler, 
    new object[] { command, CancellationToken.None });
  •  Tags:  
  • Related