C#每个属性都应执行TestMethod

问题描述 投票:1回答:2

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

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-core xunit xunit.net xunit2
2个回答
2
投票

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

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();
    }
}

2
投票

除了提供元数据外,Attribute还执行其他功能会引起不必要的复杂性。

整个自定义属性都可以删除并使用内置数据属性

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

        //Act
        profile.GoTo();

        //Assert
        profile.IsAt();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.