如何在 .net core 2.0 中模拟 IAuthorizationService

How to mock IAuthorizationService in .net core 2.0

我在我的控制器中使用这个资源授权:

var result = await _authorizationService.AuthorizeAsync(User, document, operation);

我需要测试我的控制器,我需要授权才能通过测试。

我试过了:

_substituteAuthorizationService.AuthorizeAsync(Arg.Any<ClaimsPrincipal>(), null, Arg.Any<IEnumerable<IAuthorizationRequirement>>())
            .ReturnsForAnyArgs(new AuthorizationResult(......));

但我不能 new AuthorizationResult,因为它没有 public 构造函数。

有什么想法吗?谢谢!

这里就不多说了https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.authorization.authorizationresult?view=aspnetcore-2.0

但是您可以return从静态方法

AuthorizationResult.Success()
AuthorizationResult.Failed()