测试所有端点的身份验证,.Net core 3.0

Test all endpoints for authentication, .Net core 3.0

我想构建集成测试以确保我们所有的端点都被锁定在身份验证之后。

然后我将从 swagger 中获取所有端点。 我怎样才能等待这个电话,然后将这个数据用作 memberData 或 classData?因为它是异步的。 我应该使用固定装置还是某种 ---- 数据?

    [Collection("A collection")]
    public class EndpointsTests
    {
        RouteDataFixture fixture;

        public EndpointsTests(RouteDataFixture fixture)
        {
            this.fixture = fixture;
        }

        [Theory]
        [ClassData(typeof(SomeClassWithAsyncConstructor))]
        public async Task Test_This(string path, string method)
        {
            //test the awaited data from class
            if(method == "GET"=
                var response = await fixture.GetAsync(path)

            //Check if the response is unauthorized since we didn't send a token
        }
    }

如果没有特殊原因你可以使用单元测试而不是集成测试,你可以检查你的端点是否定义了任何授权属性。例如;

    public class SomeController : Controller
    {
        [AllowAnonymous]
        public IAsyncResult Post1()
        {
            // codes...
        }

        [Authorize("some_permission")]
        public IAsyncResult Post2()
        {
            // codes...
        }

        public IAsyncResult Post3()
        {
            // codes...
        }
    }

这是你的控制器class。

    [Fact]
    public void Test()
    {
        var _endpoints = new List<(Type, MethodInfo)>(); // All endpoints in my project
        var asm = Assembly.Load("MyAssembly");
        var cType = typeof(Controller);
        var types = asm.GetTypes().Where(x => x.IsSubclassOf(cType)).ToList();
        foreach (Type t in types)
        {
            var mInfos = t.GetMethods(BindingFlags.Public | BindingFlags.Instance).Where(x => x.DeclaringType.Equals(t)).ToList();
            foreach (MethodInfo mInfo in mInfos)
                _endpoints.Add((t, mInfo));
        }

        var nonAuthEndPoints = _endpoints.Where(x => !x.IsDefined(typeof(AuthorizeAttribute)) && !x.IsDefined(typeof(AllowAnonymousAttribute)));

        nonAuthEndPoints.Should().BeEmpty();
    }

这是你的测试方法。这将检查所有端点并强制它们应该具有 AllowAnonymous 或 Authorize。

在此示例中,您的 Post1 和 Post2 端点通过了测试,但 post3 失败了。