[C#如果具有属性(XUnit),则使用using语句包围该方法]

问题描述 投票:1回答:1
public class ProfileTest
{
    [Theory, Priority(0)]
    [Roles(Role.Editor, Role.Viewer)]
    public void OpenProfilePageTest(Role role)
    {
        using(new AuthTest(role))
        {
            var profile = GetPage<ProfilePage>();
            profile.GoTo();
            profile.IsAt();
        }
    }
}

public class RolesAttribute : DataAttribute
{
    private Role[] _roles;
    public RolesAttribute(params Role[] roles)
    {
        _roles = roles;
    }

    public override IEnumerable<object[]> GetData(MethodInfo testMethod)
    {
        var data = new List<object[]>();
        foreach (var role in _roles)
            data.Add(new object[] { role });
        return data;
    }
}

public class AuthTest : Test, IDisposable
{
    public AuthTest(Role role)
    {
        AuthRepository.Login(role);
    }

    public void Dispose()
    {
        GetPage<DashboardPage>().Logout();
    }
}

如果测试方法用using(new AuthTest(role))装饰,在XUnit中是否可以用[Roles(Enum.Role)]自动包装我的测试方法?

因此,在使用using()的每种测试方法中,我不必手动使用[Roles(Enum.Role)]语句。当测试方法用[Roles(Enum.Role)]装饰时,我想添加一点魔术。

我曾想将Dispose()方法添加到RolesAttribute,但我无法在AuthRepository.Login(role)属性类中执行RolesAttribute

-编辑-

Fabio发表评论后,我将代码更改为:

public abstract class AuthTest : Test, IDisposable
{
    public void Dispose()
    {
        GetPage<DashboardPage>().Logout();
    }
}

public class ProfileTest : AuthTest
{
    [Theory, Priority(0)]
    [Roles(Role.Editor, Role.Viewer)]
    public void OpenProfilePageTest(Role role)
    {
        AuthRepository.Login(role);
        var profile = GetPage<ProfilePage>();
        profile.GoTo();
        profile.IsAt();
    }
}

现在为每个测试方法调用Dispose方法。但是我该怎么做:AuthRepository.Login(role);是用[Roles(Role)]装饰的方法中应该发生的第一件事,而无需我手动在所有测试方法中添加它?

c# .net-core xunit xunit.net xunit2
1个回答
0
投票

您是否可以使用类似HasPermission属性的内容?

这样,您可以在'HasPermission'属性的OnActionExecuting中编写使用功能。(或任何其他自定义属性,例如'logMeInAttribute:ActionFilterAttribute')


此博客介绍了角色/权限的不同方式,可能也会派上用场;Roles vs permissions

© www.soinside.com 2019 - 2024. All rights reserved.