English 中文(简体)
NET Web Api 单位测试 [授权]
原标题:.NET Web Api unit test for [Authorize]

我有一个.net网状的网状信息 如下所示:

  [ApiController]
  public class MyController : ControllerBase
  {
      [Authorize(Roles ="Admin")]
      public IActionResult MyEndpoint()
      {
        //DO STUFF
        return Ok();
      }
  }

我的问题是,如何用单位测试授权属性?如何测试如果jwt标语包含一个行政官的主张,它应该退回200个其他单位,它应该归还401个未经授权的属性。

问题回答

根据您的描述,如果您想要使用 JWT 符号将请求发送到服务器并测试该属性是否有效,您只能使用整合测试,因为 JWT 认证验证包含许多单位, 如验证、设定索赔、检查索赔角色等等,使得这项测试不是单位测试。

有关如何使用整合测试的更多细节, 您可以设置 WebApplication Facoritory 如下:

public class BasicTests 
    : IClassFixture<WebApplicationFactory<Program>>
{
    private readonly WebApplicationFactory<Program> _factory;

    public BasicTests(WebApplicationFactory<Program> factory)
    {
        _factory = factory;
    }

        [Theory]
        [InlineData("/MyController/MyEndpoint")]
        public async Task Get_EndpointsReturnSuccessAndCorrectContentType(string url)
        {
            // Arrange
            var client = _factory.CreateClient();
            var token = "YOUR_VALID_JWT_TOKEN_WITH_ADMIN_ROLE";

            // Add the JWT token to the request headers
            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");
            // Act
            var response = await client.GetAsync(url);
    
            // Assert
            response.EnsureSuccessStatusCode(); // Status Code 200-299
            Assert.Equal("text/html; charset=utf-8", 
                response.Content.Headers.ContentType.ToString());
        }
    }

更多细节, 您可以参考此 < a href=" "https://learn.microsoft. com/ en- us/aspnet/core/ test/ international- tests? view=aspnetcore- 800# 基本测试- with- default- Webapitfactfactory" rel= "nofollown norefererr" >link 。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签