【问题标题】:Unit Testing With Mediatr pipelines使用 Mediatr 管道进行单元测试
【发布时间】:2021-01-18 17:39:42
【问题描述】:

我有一个 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&lt;TResponse&gt;,这可以修复,但是这个管道将为每个请求运行,我宁愿避免。有没有更好的方法来解决这个问题?是什么原因造成的?

【问题讨论】:

    标签: .net xunit mediatr


    【解决方案1】:

    我会考虑使用 SliceFixture.cs 在您的中介处理程序上运行集成测试,就像 Jimmy Boagrd 所做的那样。

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

    多年来我一直在使用完全相同的模式,它在皮下测试中效果很好。

    【讨论】:

      猜你喜欢
      • 2020-08-04
      • 1970-01-01
      • 1970-01-01
      • 2016-11-12
      • 1970-01-01
      • 1970-01-01
      • 2017-05-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多