使用 Mediatr 管道进行单元测试

时间:2021-01-18 17:39:42

标签: .net xunit mediatr

我有一个 api 控制器,它使用 Mediatr 进行各种操作。对于其中一些操作,我需要验证用户具有正确的访问级别,因此我使用了授权管道:

public class AuthorisationPipeline<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
    where TRequest : IAuthorisedRequest<TResponse>
{
    public AuthorisationPipeline()
    {   }

    public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
    {
         //Verify User
    }
}


{
    public interface IAuthorisedRequest : IAuthorisedRequest<Unit>
    { }

    public interface IAuthorisedRequest<out TResponse> : IRequest<TResponse>
    {
        Actor Actor { get; set; }
    }
}

因此任何需要授权的请求都会继承 IAuthorisedRequest 接口。

这在运行 API 时工作正常,但是,我一直在尝试设置单元测试,这些单元测试运行端到端的 api 调用(或功能测试或皮下测试或您想调用的任何内容)。当我尝试运行这些测试时,任何不继承 IAuthorisedRequest 的请求都会引发以下异常:

System.ArgumentException : GenericArguments[0], 'UpdateUsers+Command', on 'AuthorisationPipeline2[TRequest,TResponse]' violates the constraint of type 'TRequest'.

如果我删除 where TRequest : IAuthorisedRequest<TResponse>,这可以解决,但是此管道将针对每个请求运行,我宁愿避免这种情况。有没有更好的方法来解决这个问题?是什么原因造成的?

1 个答案:

答案 0 :(得分:0)

我会像 Jimmy Boagrd 一样研究使用 SliceFixture.cs 在您的中介处理程序上运行集成测试。

您可以查看他在示例应用程序 here 中汇总的测试。

多年来我一直在使用完全相同的模式,它适用于皮下测试。