首页 > 解决方案 > C#每个属性都应该执行TestMethod

问题描述

我创建了一个自定义 xUnit 理论测试 DataAttribute,名为RoleAttribute

public class RoleAttribute : DataAttribute
{
    public Role Role { get; set; }
    public RoleAttribute(Role role, Action<Role> method)
    {
        Role = role;
        AuthRepository.Login(role);
        method(role);
    }

    public override IEnumerable<object[]> GetData(MethodInfo testMethod)
    {
        return new[] { new object[] { Role } };
    }
}

我有测试方法OpenProfilePageTest

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

我想要的是它首先执行的每个角色(属性):

AuthRepository.Login(role);(的构造函数RoleAttribute

然后继续使用OpenProfilePageTest()方法内部的代码。在它重复相同但针对第二个属性之前。

我怎样才能做到这一点,现在我正试图通过OpenProfilePageTest()在属性内部传递方法并在其构造函数中执行它来实现这一点。必须有比传递我相信的方法更好的方法来实现这一点?

标签: c#.net-corexunitxunit.netxunit2

解决方案


您可以在不通过方法的情况下实现此目的,您需要稍微修改您的属性。我更改了属性以获取您要测试的所有角色并在数据中返回它们。这是一个例子

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[]>();
        //We need to add each role param to the list of object[] params
        //This will call the method for each role
        foreach(var role in _roles)
            data.Add(new object[]{role});
        return data;
    }
}

然后在您的测试中,您只需在一个属性中传递您想要测试的所有角色,就像这样

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

推荐阅读